Symfony2: How to pass url querystring parameters to controllers?

為{幸葍}努か 提交于 2020-01-10 08:49:53

问题


Maybe I am missing something but there doesn't seem to be a way to define querystring parameters in routes in Symfony2 so that they can be passed into a controller.

For instance, instead of generating a URI like /blog/my-blog-post (from Symfony2's routing documentation) and passing it to the following route:

# app/config/routing.yml    
blog_show:
    pattern:   /blog/{slug}
    defaults:  { _controller: AcmeBlogBundle:Blog:show }

I would prefer to generate a URI like /blog?slug=my-blog-post. The problem is I can't find anywhere to define the slug parameter in the route configuration file (like its {slug} counterpart above).

Perhaps this is on purpose but then what is the best practice for working with GET parameters in the querystring?

The documentation does make mention of them in Generating URLs with Query Strings, so how to pass them into the controller?

Where I can find mention of them is Symfony2 and HTTP Fundamentals:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

// retrieve GET variables
$request->query->get('foo');

Is this the best practice for working with them inside the controller?


回答1:


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
    ...
}



回答2:


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).



来源:https://stackoverflow.com/questions/11620739/symfony2-how-to-pass-url-querystring-parameters-to-controllers

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