Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp : Check if view element exists

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...

like image 340
Frederik Van Everbroeck Avatar asked Mar 10 '11 15:03

Frederik Van Everbroeck


2 Answers

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

like image 77
Code Commander Avatar answered Nov 22 '22 15:11

Code Commander


set element name in controller:

$default_element = 'my_element';
$element = 'my_cat_element';

if ($this->theme) {
   $element_path = APP . 'views' . DS . 'themed' . DS . $this->theme . 'elements' . DS . $element . DS . $this-ext;
} else {
   $element_path = APP . 'views' . DS . 'elements' . DS . $element . $this-ext;
}
if (!file_exists($element_path)) {    
   $element = $default_element;
}
like image 24
curo Avatar answered Nov 22 '22 14:11

curo