Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - dynamically replace GET parameter's value

Is there a way to replace a GET parameter value from twig?

For example, I have a page at this address:

http://localhost/app_dev.php/test/?param1=40&sort=name

And in my twig I want to build 3 links like this:

http://localhost/app_dev.php/test/?param1=40&sort=name 
http://localhost/app_dev.php/test/?param1=40&sort=address 
http://localhost/app_dev.php/test/?param1=40&sort=code 

For now I added the "&sort" parameter once again at the end on the URL, but this solution is actually a "patch" and it sucks!

<a href="{{app.request.requesturi}}&sort=address">address</a>

In this example I only have 2 parameters, but in reality I have around 6 parameters, because the link that's generated it's obtained by submitting a .

like image 624
chris_so Avatar asked Mar 12 '13 13:03

chris_so


2 Answers

This should solve your problem:

{{ path(app.request.attributes.get('_route'),
   app.request.query.all|merge({'sort': 'address'})) }}

It gets the current route and all query parameters which are merged with the one you like to update before they are appended.

like image 108
insertusernamehere Avatar answered Nov 15 '22 10:11

insertusernamehere


Symfony/Twig path function accept optional params. If these params are part of the route, they're handled by router but if they're not, they are passed as GET parameters.

So, if your corresponding route is, for example, my_route :

<a href="{{ path('my_route', {'param1':40, 'sort':'address'}) }}">address</a>
like image 28
AlterPHP Avatar answered Nov 15 '22 11:11

AlterPHP