How do I call an element from a helper in CakePHP 2.x?
In CakePHP both helpers and elements are great ways to reuse code at the view level. I tend to use helpers more for OO style functionality and elements more for reusable chunks of HTML. In this case I have a stack of elements with a common wrapper (provided by the helper) and wanted pass the desired element as an arguemnt into the helper method. As we are no longer in the view $this->element();
is out of scope. A quick search of the API documentation (http://api.cakephp.org/2.6/class-Helper.html) revealed this is stored as a protected property; $this->_View->element();
should do the trick.
From the documentation:
$_View protected View
The View instance this helper is attached to
Implementation example:
<?php
App::uses('AppHelper', 'View/Helper');
class PanelHelper extends AppHelper{
public function panel($element, $options){
$wrapper = null;
//do stuff with options....
$wrapper .= "<strong>{$options['name']}</strong>";
$wrapper .= $this->_View->element($element);
return $wrapper
}
}
Usage example:
<?php
echo $this->PanelHelper('helper', array('name'=>'some name'));