In Symfony2, the route parameters can be automatically map to the controller arguments, eg: http://a.com/test/foo will return "foo"
/**
* @Route("/test/{name}")
*/
public function action(Request $request, $name) {
return new Response(print_r($name, true));
}
see http://symfony.com/doc/current/book/routing.html#route-parameters-and-controller-arguments
But I want to use query string instead eg: http://a.com/test?name=foo
How to do that ? For me there are only 3 solutions:
Is there another solution ?
I provide you the code for those which want to use a converter :
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Put specific attribute parameter to query parameters
*/
class QueryStringConverter implements ParamConverterInterface{
public function supports(ParamConverter $configuration) {
return 'querystring' == $configuration->getConverter();
}
public function apply(Request $request, ParamConverter $configuration) {
$param = $configuration->getName();
if (!$request->query->has($param)) {
return false;
}
$value = $request->query->get($param);
$request->attributes->set($param, $value);
}
}
services.yml :
services:
querystring_paramconverter:
class: AppBundle\Extension\QueryStringConverter
tags:
- { name: request.param_converter, converter: querystring }
In your controller:
/**
* @Route("/test")
* @ParamConverter("name", converter="querystring")
*/
public function action(Request $request, $name) {
return new Response(print_r($name, true));
}
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