i'm making a product crud in codeigniter but i have this problem with my code:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: ver
Filename: views/productos_view.php
Line Number: 51
Backtrace:
File: C:\wamp64\www\catalogo\application\views\productos_view.php
Line: 51
Function: _error_handler
File: C:\wamp64\www\catalogo\application\controllers\Welcome.php
Line: 23
Function: view
File: C:\wamp64\www\catalogo\index.php
Line: 315
Function: require_onc
Welcome.php
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('productos_view');
}
}
Controller function
//controlador por defecto
public function index(){
//array asociativo con la llamada al metodo
//del modelo
$productos["ver"]=$this->productos_model->ver();
//cargo la vista y le paso los datos
$this->load->view("productos_view",$productos);
}
Model
public function ver(){
// //Hacemos una consulta
$consulta=$this->db->query("SELECT * FROM catalogo;");
// Devolvemos el resultado de la consulta
return $consulta->result();
}
Repalce your code in Welcome controller with the below code.
class Welcome extends CI_Controller {
public function index() {
$productos["ver"] = array();
$this->load->view("productos_view",$productos);
}
}
Because you are not sending $ver in your welcome controller.
see Mr. TimBrownlaw explanation, try add this code on you controller,
public function __construct()
{
parent::__construct();
$this->load->model('productos_model');
}
put on top index function
public function index()
{
$ver = ''; //Declare blank variable
$productos = array(); //Declare blank array
$ver = $this->productos_model->ver(); //get from model
$productos["ver"] = $ver; //assigne in $productos array
//cargo la vista y le paso los datos
$this->load->view("productos_view",$productos);
}
and can you show productos_view code?
Related
I have a user entity that has an image property. When I register a user from a registration form, the image is displayed in the user's profile view and the name of the image is saved in the database. But when I want to change the profile of the user from an edit form, when sending the form, I have the following message: the file was not found
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\File(mimeTypes={ "image/jpeg" })
*/
private $picture;
private $file;
```entity User methods
/**
* Get the value of file
*/
public function getFile()
{
return $this->file;
}
/**
* Set the value of file
*
* #return self
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
``` the method in the AccountController
/**
* Permet d'afficher le formulaire d'édition du profil
* #Route("/account/profile", name="account_profile")
*
* #return Response
*/
public function profile(Request $request, ObjectManager $manager)
{
$user = $this->getUser();
$form = $this->createForm(AccountType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPicture(
new File($this->getParameter('upload_directory') . '/' . $user->getPicture())
);
$manager->persist($user);
$manager->flush();
$this->addFlash(
'success',
"Les modifications ont bien été enregistrées"
);
return $this->redirectToRoute('user_show');
}
return $this->render('account/profile.html.twig', [
'form' => $form->createView()
]);
}
I also created a pictureUploadListener entity that I declared in the service.yaml file
I have done this (https://laravel.com/docs/5.7/notifications#database-notifications), I ran the migration, I created a toArray() and a toDatabase() functions in the notification, and the notifications are correctly being sent, however, notifications are not being saved. My HablameChannel::send() method can send many messages because a certificate can have many phone numbers to notify, so I send the same notification to all of them.
This is my channel code:
<?php
namespace App\Channels;
use App\Models\Message;
use Illuminate\Notifications\Notification;
class HablameChannel
{
/**
* Send the given notification.
* Envía las mensajes de
*
* #param \App\Models\Owner $notifiable
* #param \Illuminate\Notifications\Notification|\App\Notifications\CertificateToExpire $notification
* #return void
*/
public function send($notifiable, $notification)
{
// Se consultan los mensajes de la entidad notificable, en este caso el certificado.
$messages = $notification->toHablame($notifiable);
// Send notification to the $notifiable instance...
$messages->each->send();
}
}
This is my notification code:
<?php
namespace App\Notifications;
use App\Channels\HablameChannel;
use App\Models\Certificate;
use App\Models\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class CertificateToExpire extends Notification
{
use Queueable;
/**
* Certificado por el cual se va a notificar que está a punto de caducar.
*
* #var \App\Models\Certificate
*/
protected $certificate;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Certificate $certificate)
{
$this->certificate = $certificate;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return [HablameChannel::class];
}
/**
* Get the array representation of the notification.
*
* #param \App\Models\Owner $notifiable
* #return array
*/
public function toArray($notifiable)
{
return $this->toHablame($notifiable)->toArray();
}
/**
* Obtiene los mensajes a enviar por Háblame SMS.
*
* #param \App\Models\Owner $notifiable
* #return \Illuminate\Support\Collection|\App\Models\Message[]
*/
public function toHablame($notifiable)
{
$template = setting(
'plantilla_de_vencimiento',
'CDA DEL CESAR de la 44 le recuerda que la Revisión Técnico-Mecánica del vehículo'
. ' de placa {number_plate} está por vencer.'
. ' Visítenos en la CL 44 N 23A - 46. 3205739223'
);
$engine = new \StringTemplate\Engine();
$body = $engine->render($template, [
'number_plate' => $this->certificate->number_plate,
]);
$now = Carbon::now();
return $this->certificate->recipients_to_notify->map(
function (array $recipient) use ($body, $now) {
return $this->certificate->messages()->create([
'receiver_name' => $recipient['receiver_name'],
'to' => $recipient['to'],
'body' => $body,
'reference' => 'Certificados a punto de vencer.',
]);
}
);
}
}
This is the code where I call for the notification:
$certificate->owner->notify(new CertificateToExpire($certificate));
Sorry, I just had to add the database driver to CertificateToExpire::via() method.
public function via($notifiable)
{
return [HablameChannel::class, 'database'];
}
I would like to apply the best laravel practices regarding the services + containers.
Usually when I need to use a method anywhere in my app, I do that :
class PersonneController extends Controller {
private $personne_service;
private $role_service;
public function __construct() {
$this->personne_service = new PersonneService();
$this->role_service = new RoleService();
}
/**
* Renvoi la liste des personnes d'une école de la personne connectée
* #return
*/
public function getListePersonnes(Request $request, $id_ecole = null)
{
if ($id_ecole == null){
$id_ecole = Auth::user()->id_ecole;
}
$liste_personnes = $this->personne_service->getListePersonnesMultiRecherches($request->all());
See the last line to use a method in an other class. It works fine and I have understood the mechanic !
Now I would like to do the same thing using services and containers. Here what I do :
step 1 : create a service provider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\PersonneService;
class PersonneServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('PersonneService', function ($app) {
return new App\Services\PersonneService();
});
}
}
step 2 : declare this container into my app/config file :
'providers' => [
// ....
App\Providers\PersonneServiceProvider::class,
],
step 3 : i use this method anywhere in my app. For example in a controller :
(see the commented lines vs the previous code)
class PersonneController extends Controller {
// private $personne_service;
private $role_service;
public function __construct() {
// $this->personne_service = new PersonneService();
$this->role_service = new RoleService();
}
/**
* Renvoi la liste des personnes d'une école de la personne connectée
* #return
*/
public function getListePersonnes(Request $request, $id_ecole = null)
{
if ($id_ecole == null){
$id_ecole = Auth::user()->id_ecole;
}
// $liste_personnes = $this->personne_service->getListePersonnesMultiRecherches($request->all());
$personne_service = app()->make('PersonneService');
$liste_personnes = $personne_service->getListePersonnesMultiRecherches($request->all());
It does not work. I have this error :
Class PersonneService does not exist
in Container.php (line 729)
My questions :
what are the problems ? (I read the official doc + a lot of tutorials on this topic)
is it really a good practice to do that ? or do you think that my first technich is well too ?
Thanks for your feedbacks. Merci
Dominique
I have created a repository to manage the upload image using Intervention/Imagelibrary but when I try to save an image I get Call to a member function encode() on null.
This is my interface:
namespace App\Repositories\MeetMount\ImageUploader;
use Illuminate\Http\Request;
interface ImageContract {
public function getExt($filename);
public function setFolder($folderName);
public function getRandomFilename($fileName);
public function addWatermark($watermarkName);
public function resize($width, $height);
public function getFileName();
public function save(Request $file);
}
This is my concrete class:
namespace App\Repositories\MeetMount\ImageUploader;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Intervention\Image\Image;
class InterventionImageRepository implements ImageContract {
/**
* #var Image
*/
private $image;
/**
* #var $folder
*/
private $folder;
/**
* InterventionImageRepository constructor.
*
* #param Image $image
*/
public function __construct( Image $image )
{
$this->image = $image;
}
/**
* Restituisce l'estensione dell'immagine
*
* #param $fileName
* #return string
*/
public function getExt( $fileName )
{
$pos = strrpos( $fileName, '.' );
$ext = substr( $fileName, $pos, strlen( $fileName ) );
return $ext;
}
/**
* Imposta la cartella dove salvare l'immagine
*
* #param $folderName
* #return $this
*/
public function setFolder( $folderName )
{
$folderPath = public_path( $folderName );
if( ! File::exists( $folderPath ) )
{
File::makeDirectory( $folderPath );
}
$this->folder = $folderPath;
return $this;
}
public function getRandomFilename( $fileName )
{
// TODO: Implement getRandomFilename() method.
}
/**
* Aggiungi watermark
*
* #param $watermarkName
* #return $this
*/
public function addWatermark( $watermarkName )
{
$watermarkPath = public_path( 'images/watermarks/' . $watermarkName );
$this->image->insert( $watermarkPath );
return $this;
}
/**
* Salva il file
*
* #param $file
* #return $this
*/
public function save( Request $request )
{
$file = $request->file('immagine');
$fileFolder = $this->folder . '/' . $file->getClientOriginalName();
$this->image->save( $fileFolder );
return $this;
}
public function getFileName()
{
// TODO: Implement getFileName() method.
}
public function resize( $width, $height )
{
// TODO: Implement resize() method.
}
}
and this is the store method:
public function store( CreatePlaceRequest $request )
{
$this->imageRepository->setFolder('cartella-prova')->save($request);
}
When I submit the form I get:
FatalErrorException in Image.php line 119:
Call to a member function encode() on null
in Image.php line 119
at FatalErrorException->__construct() in HandleExceptions.php line 133
at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 118
at HandleExceptions->handleShutdown() in HandleExceptions.php line 0
at Image->encode() in Image.php line 139
at Image->save() in InterventionImageRepository.php line 96
at InterventionImageRepository->save() in PlacesController.php line 80
at PlacesController->store() in Controller.php line 76
The problem should be here: at Image->save() in InterventionImageRepository.php line 96
and that line is in the concrete class, in the save method:
$this->image->save( $fileFolder );
Can someone help me to find the problem?
According to the error:
Call to a member function encode() on null ...
This means you are trying to save an image while it doesn't received an image - null.
The problem is with save function in your InterventionImageRepository class. I've modified it to check if there is an image or not.
Also consider your image filed name has typo(immagine). Make sure you use the same word in your form input feild with type=file. Else correct it to have same name both in controller/class files and frond end views. Also make sure you are using enctype="multipart/form-data" in your <form> tag.
<form method="post" action="target-path" enctype="multipart/form-data">
Otherwise files will not send to server along with the form values.
/**
* Salva il file
*
* #param $file
* #return $this
*/
public function save( Request $request )
{
//first check if the file received
if($request->hasFile('immagine')){
$file = $request->file('immagine');
$fileFolder = $this->folder . '/' . $file->getClientOriginalName();
$this->image->save( $fileFolder );
return $this;
}else{
//Do some necessary outputs here
//may be store a message to session and display it to user in the view
//or return a boolean value and check for it in your store method
}
}
Refer to this Laravel's official documentation and improve your scripts: https://laravel.com/docs/5.2/requests#files
I am starting out with codeigniter, but the documentation is horribly written and doesn't actually work with the new version. My issue is that I cannot call a function within a model.
Here is my model: User.php
<?php
class User extends CI_Model {
function __construct()
{
parent::__construct();
}
}
function test($x)
{
return $x;
}
?>
And my controller: welcome.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->model('User');
echo $this->User->test('darn');
$this->load->view('welcome_message');
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
Check your {}s, your test function is outside your User class. Move it inside the class, then $this->User->test() will work.
<?php
class User extends CI_Model {
function __construct()
{
parent::__construct();
}
function test($x)
{
return $x;
}
}
?>
There's nothing "horrible" about the documentation.