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 "view_helpers" => "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 var_export(array('name'=>$name, 'hasName' => $this->has($name), 'autoloadAddInvokableClass' => $this->autoAddInvokableClass, 'class_exists'=>class_exists($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');

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

The author does not allow comments to this entry

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Markdown format allowed
Form options