How do I access a routed parameter from inside a c

2019-06-14 08:19发布

问题:

This is the route...

'panel-list' => array (
    'type' => 'Segment',
    'options' => array (
        'route'    => '/panel-list/:pageId[/:action]',
        'constraints' => array (
            'pageId' => '[a-z0-9_-]+'
        ),
        'defaults' => array (
            'action' => 'index',
            'controller' => 'PanelList',
            'site' => null
        ),
    ),
),

What do I need to put in here....

public function indexAction()
{
    echo ???????
}

to echo the pageId?

回答1:

In beta5 of zf2 it changed to easier usage so you don't need to remember different syntax for every different type. I cite:

New "Params" controller plugin. Allows retrieving query, post, cookie, header, and route parameters. Usage is $this->params()->fromQuery($name, $default).

So to get a parameter from the route, all you need to do is.

$param = $this->params()->fromRoute('pageId');

This can also be done with query ($_GET) and post ($_POST) etc. as the citation says.

$param = $this->params()->fromQuery('pageId');
// will match someurl?pageId=33

$param = $this->params()->fromPost('pageId');
// will match something with the name pageId from a form.

// You can also set a default value, if it's empty.
$param = $this->params()->fromRoute('key', 'defaultvalue');

Example:

$param = $this->params()->fromQuery('pageId', 55);

if the url is someurl?pageId=33 $param will hold the value 33. if the url doesn't have ?pageId $param will hold the value 55



回答2:

Have you tried

$this->getRequest()->getParam('pageId')


回答3:

$this->getEvent()->getRouteMatch()->getParam('pageId');