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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With