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'])); ?>
Share:
11,593

Related videos on Youtube

meotimdihia
Author by

meotimdihia

Updated on June 04, 2022

Comments

  • meotimdihia
    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
    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
    vitto almost 13 years
    I could find it useful if you need to highlight the selected section on a visual menu. Or am I missing something too?
  • aWebDeveloper
    aWebDeveloper over 12 years
    thsi may not work blog.zahidur.com/how-to-get-model-name-in-cakephp read the comments
  • 23kulpamens
    23kulpamens over 12 years
    Thats why i use "classify" instead of "singularize". And this solution works fine. Check the Inflector documentation book.cakephp.org/view/1479/Class-methods
  • user6972
    user6972 over 10 years
    What about when you need to create a form dynamically in an element?
  • António Almeida
    António Almeida almost 9 years
    Bad idea, look at this example: Territory > Territories, this will not work with your code.
  • Mirko Pagliai
    Mirko Pagliai over 8 years
    This 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.
    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".

Related