Search code examples
phprouteszend-framework2

Zend Framework 2 getting URL from route


What I'm trying to do is generate a URL using the url view helper in Zend Framework 2

The URL that I am trying to generate should be my-website.com/app/## (where ## is equal to the "ownerID")

What happens when I generate this using the view helper like this:

$this->url('mymodule', array('action'=>'show', 'ownerID'=>'28'));

is it only generates "my-website.com/app", but I am expecting "my-website.com/app/28" based on the routing configuration.

Here is the route information from my module.config.php file

'router' => array(
'routes' => array(
    'mymodule' => array(
        'type' => 'segment',
        'options' => array(
            'route'    => '/app',
            'defaults' => array(
               'controller' => 'MyModule\Controller\MyModule',
               'action'     => 'show',
            ),
        ),
        // Defines that "/app" can be matched on its own without a child route being matched
        'may_terminate' => true,
        'child_routes' => array(
            'archive' => array(
                'type' => 'segment',
                'options' => array(
                    'route'    => '/:action[/:ownerID[/:clientID]]',
                    'defaults' => array(
                    ),
                    'constraints' => array(
                       'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                       'ownerID'     => '[0-9]+',                               
                       'clientID'     => '[0-9]+',
                    )
                ),
            ),
            'single' => array(
                'type' => 'segment',
                'options' => array(
                    'route'    => '/:ownerID[/:clientID]',
                    'defaults' => array(
                        'action'     => 'show',
                    ),
                    'constraints' => array(
                       'ownerID'     => '[0-9]+',
                       'clientID'     => '[0-9]+',
                    )
                ),
            ),
        )
    ),
)
),

The same behavior occurs when using $this->redirect()->toRoute.

All of the routes work as expected when you type them manually, it is just the generation of the URL that has me stumped.


Solution

  • To more directly answer the question, it doesn't do what you expect because you are only passing the top level route name ("mymodule") to the URL helper. The ownerID is part of a child route.

    What you actually want is:

    $this->url('mymodule/archive', array('action'=>'show', 'ownerID'=>'28'));
    

    (or possibly mymodule/single, depending on the output you want).