Cakephp : Check if view element exists

Frederik Van Everbroeck picture Frederik Van Everbroeck · Mar 10, 2011 · Viewed 7.7k times · Source

Is there a way to check if an element exists for a view? I want to load a different element according to a category it belongs to but not all categories have an element for it...

Answer

Code Commander picture Code Commander · Jun 5, 2013

As of CakePHP version 2.3 you can use the View's elementExists method:

if($this->elementExists($name)) { ... }

In older versions of 2.x you can do:

if($this->_getElementFilename($name)) { ... }

But sadly in version 1.3 it looks like the only way is to know the full path and do something like:

if(file_exists($path . 'elements' . DS . $name . $ext)) { ... }

That is what they do in the 1.3 source code, but there is some complexity around getting $path from various plugins and checking each of those paths. (See link below.)

Sources:

http://api.cakephp.org/2.3/class-View.html#_elementExists

http://api.cakephp.org/2.0/source-class-View.html#722

http://api.cakephp.org/1.3/source-class-View.html#380