Reputation: 108
Fairly experienced programmer but new to CakePHP 2.1 and spending my day struggling to get a custom Helper to work in View by following the manual: http://book.cakephp.org/2.0/en/views/helpers.html
I've not been able to find an answer and would greatly appreciate any Cake expertise.
My helper file in app/Helper/EntriesHelper.php:
App::uses('AppHelper', 'View/Helper');
class EntriesHelper extends AppHelper {
public function __construct(View $view, $settings = array()) {
parent::__construct($view, $settings);
}
public function spanWrapper($content) {
if(substr($content,0,1) == "@") {
return "<span class='label label-warning'>$content</span>";
}
else if(substr($content,0,1) == "#") {
return "<span class='label label-default'>$content</span>";
}
else if (substr($content,0,4) == "http" || substr($content,0,3) == "www") {
return "<span class='label'>$content</span>";
}
return $content;
}
}
And my controller in app/Controller/EntriesController:
App::uses('AppController', 'Controller');
class EntriesController extends AppController {
public $helpers = array('Form', 'Html', 'Js', 'Time');
#public $components = array('RequestHandler');
#public $viewClass = 'Json';
public function index() {
$helpers[] = 'spanWrapper';
$this->Entry->recursive = 1;
$this->set('entries', $this->paginate());
#$this->set('_serialize', array('entries'));
}
}
But a call from my View fails:
$this->Entries->spanWrapper($entry['Entry']['title']);
With the error:
Notice (8): Undefined property: View::$Entries [CORE/Cake/View/View.php, line 806]
Fatal error: Call to a member function spanWrapper() on a non-object in <path removed>/app/View/Entries/index.ctp on line 35
So the notice of undefined property is presumably causing the fatal error ... but why so, if it's implemented per the cookbook?
Darren
Upvotes: 2
Views: 7646
Reputation: 10306
If you want to use your helper in the entire controller, you should add it to the $helpers
array in your EntriesController
:
class EntriesController extends AppController {
public $helpers = array('Form', 'Html', 'Js', 'Time', 'Entries');
/* ... */
}
If you need the helper in your entire application, you can add it to the AppController
the same way.
If on the other side you only need it in one single view, you may choose to only load it there dynamically. In your view, call HelperCollection->view()
just before you want to use the helper for the first time:
$this->Helpers->load('Entries');
All three methods are documented very well in the CakePHP book.
Upvotes: 0
Reputation: 17967
The correct syntax is $this->helpers[] = 'spanWrapper';
when loading a helper within a method, or add it to your public $helpers
array instead.
Upvotes: 4