Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Call to a member function find() on a non-object in cakephp controller

Tags:

php

cakephp

I'm new to cakephp and tried to generate some CRUD operations with the console tool. It works fine except for one table (the biggest).

When trying to add a new element, it returns:

Error: Call to a member function find() on a non-object File: C:\wamp\www\cakephp\app\Controller\ChantiersController.php
Line: 50

Here is the line 50 and beyond:

    $programs = $this->Chantier->Program->find('list');
    $etats = $this->Chantier->Etat->find('list');
    $types = $this->Chantier->Type->find('list');
    $champsLibres = $this->Chantier->ChampsLibre->find('list');
    $feuillesDeRoutes = $this->Chantier->FeuillesDeRoute->find('list');
    $directionsPilotes = $this->Chantier->DirectionsPilote->find('list');
    $this->set(compact('programs', 'etats', 'types', 'champsLibres',    
            'feuillesDeRoutes', 'directionsPilotes'));
like image 920
L. Sanna Avatar asked Dec 08 '22 22:12

L. Sanna


1 Answers

TLDR / Answer:

You can either fix the association, or load the model, and remove the through-call (the ->Chantier portion:

$this->loadModel('Program');
$programs = $this->Program->find('list');

Details / Explanation:

That error basically means you're trying to call find() on a model that isn't loaded in the controller.

By default, the Controller's model is loaded. And, as you're doing, you can use a model THROUGH a loaded model. (if the associations are set up correctly).

For example:

//ChantiersController
$this->Pizza->find('all'); //ERROR - Pizza model isn't loaded

To resolve this, just load the model prior to trying to use it:

$this->loadModel("Pizza");
$this->Pizza->find('all'); //All is good - loaded on the line above

In your case, since it looks like you're using associations with the Chantier model to find through other models, it's likely the association between the two models is not correct.

like image 200
Dave Avatar answered May 19 '23 07:05

Dave