1

In my symfony page there is a group of checkboxes, so they have the same name :

<input type="checkbox" name="opt[]" value="1"> Option 1
<input type="checkbox" name="opt[]" value="2"> Option 2
...

I check only one box and submit, the URL in the browser looks like this: http://localhost/list?opt[]=1

In my twig I have this instruction :

<link rel="canonical" href="{{ app.request.uri }}">

In the HTML source code I have this :

<link rel="canonical" href="https://localhost/list?opt%5B0%5D=1">

And now the browser says the canonical URL is different from the current one !

How can I prevent twig to encode square brackets ? And why is he adding a 0 betwen them ??

Regards

Sami
  • 717
  • 6
  • 28
  • Why don't you just switch to `POST` instead of `GET`? – DarkBee Oct 28 '19 at 19:38
  • Because I'm making 301 redirects from old URLs to news ones, so I have to send parameters with GET – Sami Oct 29 '19 at 08:08
  • 1
    What u are seeing is actually the correct (encoded) URL. Your browser actually "tricks" you into think that `example.com/?foo[]=bar` is a [valid `url`](https://stackoverflow.com/questions/7109143/what-characters-are-valid-in-a-url), which it's not. You should write a filter which removes the querystring from `app.request.uri` to find the correct canonical url – DarkBee Oct 29 '19 at 08:14
  • I see, thanks :) a simple replace() solved the problem, but still can't figure out why there is a 0 in the displayed URL ! – Sami Nov 06 '19 at 09:31
  • Because you have an input named `opt[]`? How otherwise would you track which of the two checkboxes are checked if the browser did not add an index to it? – DarkBee Nov 06 '19 at 09:34
  • remove the brackets and just name all your checkboxes `opt` – Peyman Mohamadpour Nov 11 '19 at 18:35
  • @Pmpr that is invalid. The only value posted then would be the last checked checkbox – DarkBee Nov 19 '19 at 11:48
  • @DarkBee All parameters for checkboxes are posted even if they are all named `opt` instead of `opt[]`. PHP on the server side has a convention where it automatically creates an array for parameter names that end in `[]`. However, you are free to parse the query string yourself in PHP and create arrays for any parameter names. – Stephen Ostermiller Mar 22 '22 at 10:16
  • @StephenOstermiller That is incorrect, see [demo](https://www.darkbee.be/stack/checkbox/index.php) - The last selected value overwrites the other selected checkboxes – DarkBee Mar 22 '22 at 10:22
  • It is actually PHP's parsing into `$_POST` that throws the info away. If you get the POST data from `file_get_contents("php://input")` in PHP you will see that it has all the checked values. – Stephen Ostermiller Mar 22 '22 at 10:29
  • Why go over the trouble to parse `opt=1&opt=2&opt=3` into an array? – DarkBee Mar 22 '22 at 10:38
  • So that you don't have to use ugly square brackets that need to be encoded in your URLs. – Stephen Ostermiller Mar 22 '22 at 11:26

0 Answers0