简体   繁体   中英

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;
            }
        }
    }
?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM