Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 - When and why does a route parameter get automatically converted?

Tags:

symfony

I have this route:

pfs_platform_home:
path:      /{page}/{reset}
defaults:  { _controller: PFSPlatformBundle:Advert:index, page: 1, reset: true }
requirements:
    page: \d*
    reset: true|false

If I use a link without specifying anything for reset, the router uses the default value and in my indexAction, the reset parameter is automatically converted to Boolean true. i.e.:

<li><a href="{{ path('pfs_platform_home') }}">Inicio</a></li>

But when I do that, this time $reset appears as a string 'false' in my indexAction, not a Boolean:

<a href="{{ path('pfs_platform_home', {'page': p, 'reset': 'false'}) }}">{{ p }}</a>

What am I missing?

like image 698
Roubi Avatar asked Sep 12 '25 02:09

Roubi


1 Answers

URL paths and parameters are always strings. If you have an URL like

http://example.com/page/true?foo=2&bar=false

the server cannot know that the true should be interpreted as boolean, while foo is supposed to be an integer and bar is supposed to be boolean, too.

If you want to process URL parameters, always pass and treat them as strings.

Later, you can validate them (e.g. is_numeric will tell you if a string represents a number) or transform them to other types.

What you're also experiencing here is YAML's handling of unquoted strings:

  • Strings may generally be left unquoted, if they don't contain a character that has a meaning in YAML.

  • But: true in YAML is boolean true. Therefore, your default reset: true is indeed a boolean value. Declare it as reset: "true" and it should work. The reset: true|false should be fine, IMO (didn't test it, but this is treated as a regex, so it should be interpreted as string.)

like image 94
lxg Avatar answered Sep 15 '25 22:09

lxg