Skip to content

Zend Framework 2 - Use Own View Helpers In A Controller

Assuming you had created your view helper called "MyViewHelper", placed in in "Application\src\Application\View\Helper" and added it as "invokable" in your "module.config.php" (section "viewhelpers" => "invokables").

After adding it to your "module.config.php", you can use it in your templates and everything is working as expected.
But what happens when you need that special view helper in your controller?

First idea would be to code something like the following lines in your controller.

$this->getServiceLocator()->get('viewhelpermanager')->get('MyViewHelper');

To bad, this won't work. Do you want to debug it? just add the following line at the beginning of "AbstractPluginManager::get()" and search for your "MyViewHelper" call.
echo varexport(array('name'=>$name, 'hasName' => $this->has($name), 'autoloadAddInvokableClass' => $this->autoAddInvokableClass, 'classexists'=>classexists($name)), true);

"class_exists" will return a false since your alias is not available at this point. How to solve this problem? Simple adapt your view helper call the following way.
$this->getServiceLocator()->get('viewhelpermanager')->get('\Application\View\Helper\MyViewHelper');

Translate to de es fr it pt ja