pmac89
pmac89

Reputation: 418

CakePHP: Controller not finding Model function

So, I'm getting a fatal error because the method is undefined when the controller calls the method. Though this is not true as the method is inside the classes model.

StudentsController.php

<?php
    class StudentsController extends AppController{

        public function index(){
            $students = $this->Student->find('all');    
            $this->set('students', $students);
        }

        public function add(){
            if($this->request->is('post')){
                $this->formatData($this->request->data);
            }
        }
    }

?>

And then my model: Student.php (Model)

<?php   
    class Student extends AppModel{
        var $studentData;

        public function formatData($studentData){
            if(is_null($studentData)){
                return false;
            }else{
                echo $studentData;
            }
        }
    }
?>

Upvotes: 0

Views: 528

Answers (1)

ndm
ndm

Reputation: 60463

You're not invoking the method on the model, but on the controller where there is no such method available, hence the error.

While the controller may automatically load the model, it doesn't expose its API, it just makes an instance of the model available via magic property accessors.

So instead of

$this->formatData($this->request->data);

you have to invoke the method on the model like this:

$this->Student->formatData($this->request->data);

See also

Upvotes: 2

Related Questions