how to pass params using a route in Zend Framework

2019-07-31 16:33发布

i have a router test/view and i would like to pass some params like test/view/id/123.

Im not sure how to add those params in the zf2 router.

'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(
                    'view' => array(
                        'type' => 'Literal',
                        'options' => array(
                            'route' => '/view',
                            'defaults' => array(
                                'controller' => 'Index',
                                'action'     => 'view',
                            ),
                        ),
                    ),
                ),
            ),
        ),
),

i setup view as a child route but not sure where to add those params.

i've tried 'route' => '/view/:id/:value' and

'defaults' => array(
    'controller' => 'Index',
    'action'     => 'view',
    'id'         => 'value',
)

but they don't seem to work

i am trying to understand how all this works.

any ideas? thanks

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-31 17:09
'router' => array(
    'routes' => array(
        'test-view' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/test/view/:testId[/]',
                'constraints' => array(
                    'testId'     => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'Test\Controller\Index',
                    'action' => 'view'
                ),
            ),
        ),

In your ControllerAction you can then get the parameter "testId" by using:

$this->params('testId');

Btw: The above route gives you an url like this: /test/view/123 - I thought you may get rid of the "id" param.

If you want to create a link to one kind of this pages, you can use $this->url('test-view', array('testId' => 123)) in one of your views.

查看更多
登录 后发表回答