URL ViewHelper and Child Routes in ZF2
This blog post is older than 4 years and may no longer be valid.
1 min read

URL ViewHelper and Child Routes in ZF2


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.

/test/index/my-action

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( 'test/default', array('action' => 'my-action', 'controller' => 'index') );

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