URL ViewHelper and Child Routes in ZF2

Reading Time: < 1 minute

Given this route configuration for a module

  'router' => array(
        'routes' => array(
            'test' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/test',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Test\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                'may_terminate' => true,
                'child_routes' => array(
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'defaults' => array(

I wanted to create an URL using the ViewHelper which directly links to an action of the Index Controller, e.g.


To achieve this, it is important (and not so obvious, maybe) to append the name of the child route to the name of the parent route separated with a slash, e.g.

echo $this->url(
          array('action' => 'my-action', 'controller' => 'index')

otherwise the helper won’t care about the child route and only link to /test. Tricky…

3 thoughts on “URL ViewHelper and Child Routes in ZF2”

  1. First post I found with the answer. The Zend skeleton application puts a child route under the application route by default and it was certainly unclear how to utilize it in the view helper. I’ve been using ZF2 for a few years now and had never even tried to use that model of routing until recently. Thanks for the help.

  2. In this post I found the answer for my problem. I am amazed it is not there anywhere to be found so easily although so many people would need it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.