How get name of current model this view context is attached to?
11,593
Solution 1
In controller:
$this->modelClass
Solution 2
Try this
Inflector::classify( $this->params['controller']);
this should change your controller name in to model name. And you can do it of course from view level.
Solution 3
yes you can, you need to tell your model to tell its name. so write a function in your model like:
function myname(){
return $this->name;
}
and now your controller can ask your models for their names.
Solution 4
Use Inflectors to achive your wanted result:
<?php $model = Inflector::camelize(Inflector::singularize($this->params['controller'])); ?>
Related videos on Youtube
Author by
meotimdihia
Updated on June 04, 2022Comments
-
meotimdihia almost 2 years
in API , call $this->model will return model'sname but it dont work.
http://api13.cakephp.org/class/view
is api cakephp false ? even $view->modelId dont work, too.
-
jason over 13 years"I can't think of one case which a Model's name is relevant to the view" - Exploring how cakePHP works?
-
vitto almost 13 yearsI could find it useful if you need to highlight the selected section on a visual menu. Or am I missing something too?
-
aWebDeveloper over 12 yearsthsi may not work blog.zahidur.com/how-to-get-model-name-in-cakephp read the comments
-
23kulpamens over 12 yearsThats why i use "classify" instead of "singularize". And this solution works fine. Check the Inflector documentation book.cakephp.org/view/1479/Class-methods
-
user6972 over 10 yearsWhat about when you need to create a form dynamically in an element?
-
António Almeida almost 9 yearsBad idea, look at this example:
Territory
>Territories
, this will not work with your code. -
Mirko Pagliai over 8 yearsThis is partially true, because if the model is part of a plugin, it will return the name including plugin (eg,
Plugin.Model
). You may need to split the name -
Berry M. almost 7 years@ToniAlmeida is right, use
Inflector::singularize($controller)
instead. This might also have weird results if your controller /starts/ with an "s".