34
votes

I'm trying to manipulate the query string values in a URL.

I can get the current URL or route either from the Request object or Twig's functions, but it's the query string I'm struggling with.

I don't need app.request.attributes.get('_route_params') as this gets the query string params that are in the route.

I need to get query string params that are actually in the URL.

I want to be able to do the two things listed below in both Symfony2 (in a PHP controller) and Twig (in a Twig template):

  1. Get all current query string values in the URL and display them

  2. Do 1, but change one of the query string values before displaying them

I can't find anyone who knows how to do this.

4

4 Answers

64
votes

You can use app.request.query.all to get your query strings.

If you want to change a param in Twig you can do this

{% set queryParams = app.request.query.all %}
{% set queryParams = queryParams|merge({queryKey: newQueryValue}) %}
5
votes

To get the query string "https://stackoverflow.com?name=jazz"

{{ app.request.query.get('name') | default('default value if not set'); }}
4
votes

Into controller

use Symfony\Component\HttpFoundation\Request;

public function fooAction(Request $request)
{
  $params = $request->query->all();
}

please, pay attention: $request->query->all(); will return an array with keys named as query parameters

Into twig

As long you pass from controller (read this as always) you can pass your parameters to a view in that way

use Symfony\Component\HttpFoundation\Request;

public function fooAction(Request $request)
{
  $params = $request->query->all();
  return $this->render('MyFooBundle:Bar:foobar.html.twig', array('params' => $params));
}

Into your twig template foobar.html.twig you can access all query string parameters simply by using the params variable.

e.g with this request URL: http://example.com/?foo=bar&secondfoo=secondbar

{% for paramName, paramValue in params %}
  <div>{{ paramName }}: {{ paramValue }}</div>
{% endfor %}
<div>{{ params.secondfoo }}</div>

twig output:

<div>foo: bar</div>
<div>secondfoo: secondbar</div>
<span>secondbar</span>

Another method is to use app.request.query.all in twig, without passing anything to twig from your controller.

Final note

If you want to modify one of those parameters when passing an array to twig from your controller, simply change one of the array values, as you would with normal values (i.e.: $params['id'] = $params['id'] - 1;)

0
votes

Hi Stephen we have tried ur solution to get the value but it going to default value. http://localhost:4000/about/investors/key-dates-and-events-details?year=2017#q1

i have used like this on my twig file

Please let me know.