How can I create functions that can be called in view (like in the index.ctp)?
I just wrote a function in one of my controllers:
public function getName($id) {
$name = $users
->find()
->where(['id' => $id ])
->first()
->username;
return $name;
}
The function should return the username according to the $id passed as a parameter. I just want to know how can I call a function from within my views. I'm getting this error:
"Error: Call to undefined function getName()"
You can do it, but it is against MVC-model and is not in anyway recommended.
Namespace\ControllerName::getName(1)
You should really consider taking look CakePHP manual and understand, how to set variables to view from controller http://book.cakephp.org/3.0/en/views.html#setting-view-variables
Other option would be making AJAX-request to your controller, if you want get data based on for e.g. user actions in view.
For doing such type of work you may use cakePHP Cell
//src/View/Cell/UserCell.php
namespace App\View\Cell;
use Cake\View\Cell;
class UserCell extends Cell{
public function getName($id) {
$users = TableRegistry::get('Users');// or may use $this->loadModel('Users');
$name = $users->find()->where(['id' => $id ])->first()->username;
return $name;
}
}
Now you can call from view
echo $this->cell('User::getName', [$id]);
Here is the Official Doc