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...
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With