Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3 - Route with multiple optional parameters

I have a route with multiple parameters and I want to define default values when it's empty. I didn't find something similar on SO...

My Route (yml) :

app_product_show_range_tag:
path: 'list-range{range_id}-tag{tag_id}-{name_slug}/{page}'
methods: 'GET'
defaults:
    _controller: 'AppBundle:Product:showRangeTag'
    page: 1
    tag_id: 2
    range_id: null
requirements:
    name_slug: '([a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)'
    tag_id: '\d+'
    range_id: '\d+'
    page: '\d+'

My Controller (begin ) :

/**
 * Show a range
 * @ParamConverter("productRange", options={
"mapping": {"range_id": "productRangeId", "locale": "locale"},
"repository_method": "findOneById",
"map_method_signature" = true
})
 *     @ParamConverter("productTag", options={
"mapping": {"tag_id": "productTagId", "locale": "locale"},
"repository_method": "findOneById",
"map_method_signature" = true
})
 */
public function showRangeTagAction(ProductRange $productRange = null, ProductTag $productTag = null, string $name_slug, int $page)
{ [...]

I don't understand what is wrong... I defined all default values, the controller too.

I did a quick demo at the url : https://streamable.com/1paw

Don't hesitate to ask more information !

like image 865
Snow Avatar asked Mar 07 '26 05:03

Snow


1 Answers

For what I can see your requirements regexp are wrong, or do not match what you're trying to do on your demo

requirements:
name_slug: '([a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)'
tag_id: '\d+'
range_id: '\d+'
page: '\d+'

\d+ means that you must provide at least a number. This explains the 404 response code you get on your demo. Use of \d* will solve this. You'll be allowed to use the url you're typing.

One more thing, unrelated. In PHP you're supposed to provide first the arguments without default values, as stated here : php manual

Hope it helps you.

like image 74
katchou Avatar answered Mar 08 '26 18:03

katchou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!