Configuring a ZF2 view helper before rendering

The currencyFormat view helper is very easy to use:

When I was reading the documentation for the currencyFormat view helper, I discovered that you could configure the currency code and locale once rather than in every call:

This is obviously useful, but even more useful would be if we could set it once by default and then override if we need to in a specific call.

The easiest way to do this is to use an event listener on the View event within a modules's onBootstrap method, like this:

Now we can simply do call currencyFormat() with the value in our view script:

9 thoughts on “Configuring a ZF2 view helper before rendering

  1. Nice one Rob. We've also got a method in our own AbstractActionController called getViewHelper($helperName) which basically just does this:

    return $this->getServiceLocator()->get('viewhelpermanager')->get($helperName);

    I think it is useful if you need to "configure" a view helper on a per-action basis (rather than on a global basis like your example).

  2. This may be a rookie question, but where does $sm from 'use($sm)' get defined in your onBootstrap method above?

  3. I think that better approach is to add initializer to the ViewHelperManager. So if you already have getViewHelperConfig() method in your Module.php, add "initializers" section to its return value:

  4. I use this Method to add the Dojotoolkit to the HeadScript but as test, i noticed that the 'ZendViewView' triggers twice is there any hook that calls only once during the Render event. thanks :)

  5. Nice post. But i like the solution to set up my view helpers in module.config.php, like this:

Comments are closed.