How to add custom view helpers to Zend Framework 2

I have earlier asked this question, and I got good answers there.
However, that was for beta4, and no longer works.

So where and how do I add my own view helpers to ZF2?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You should add them to your module.config.php under view_helpers like this:

'view_manager' => array(
    'template_path_stack' => array(
        'ModuleName' => __DIR__ . '/../view',
    ),
),

'view_helpers' => array(
    'factories' => array(
        'showmessages' => function($sm) {
            $helper = new ModuleName\Helper\MessageShower();
            // do stuff with $sm or the $helper
            return $helper;           
        },
    ),
    'invokables' => array(
        'selectmenu' => 'ModuleName\Helper\SelectMenu',   
        'prettyurl'  => 'ModuleName\Helper\PrettyUrl',
    ),  
),

Here I show two ways of creating the helpers. If all they need to do is to be instantiated, just add their name (including namespace) as invokables. If you need to do stuff with them or the ServiceManager, create them through the factories keyword.

Solution 2

The beta5 had a BC regarding the servicemanager. This applies for the view helper manager as well. Have a look here – there’s even an example for view helpers a bit down too.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply