How do I access a routed parameter from inside a controller?

落爺英雄遲暮 提交于 2019-12-08 13:43:48

问题


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');



来源:https://stackoverflow.com/questions/11627116/how-do-i-access-a-routed-parameter-from-inside-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!