Symfony2: How to pass url querystring parameters to controllers?

▼魔方 西西 提交于 2019-11-30 04:47:59

To work with GET / POST parameters in a controller that extends Symfony\Bundle\FrameworkBundle\Controller\Controller:

public function updateAction()
{
    $request = $this->getRequest();
    $request->query->get('myParam'); // get a $_GET parameter
    $request->request->get('myParam'); // get a $_POST parameter
    ...
}

For a controller which does not extend the Symfony base controller, declare the request object as a parameter of the action method and proceed as above:

public function updateAction(Request $request)
{
    $request->query->get('myParam'); // get a $_GET parameter
    $request->request->get('myParam'); // get a $_POST parameter
    ...
}

You can't specify your query string parameters in the routing configuration files. You just get them from the $request object in your controller: $request->query->get('foo'); (will be null if it doesn't exist).

And to generate a route with a given parameter, you can do it in you twig templates like that :

{{ path(route, query|merge({'page': 1})) }}

If you want to generate a route in your controller, it's just like in the documentation you linked:

$router->generate('blog', array('page' => 2, 'category' => 'Symfony'));

will generate the route /blog/2?category=Symfony (the parameters that don't exist in the route definition will be passed as query strings).

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