Search code examples
symfonysymfony-3.3

Optional text on Symfony router


I'm trying something with the Symfony router but I cannot achieve what I'm aiming to.

Indeed I want to add an optional text to this path, especially for the /page-{page}. So I'm asking if it's possible to have two possibilities for the same router path, like the following ones:

  • /topic/{id}
  • /topic/{id}/page-{page}

routing.yml:

utm_forum_forum:
    path:     /forum/{id}/page-{page}
    defaults:
        _controller: UTMForumBundle:Forum:forum
        page: 1
    requirements:
        id: \d+
        page: \d+

Thanks for reading, and if I'm not clear enough I can re-explain :)


Solution

  • You need to include routes for all possible configurations.

    So, if your page slug is optional, your route table should look something like:

    utm_forum_forum_default:
        path:     /forum/{id}
        defaults:
            _controller: UTMForumBundle:Forum:forum
            page: 1
        requirements:
            id: \d+
    
    utm_forum_forum:
        path:     /forum/{id}/page-{page}
        defaults:
            _controller: UTMForumBundle:Forum:forum
        requirements:
            id: \d+
            page: \d+
    

    That should provide a default value of page 1 when the page slug is omitted entirely, or require something in the form page-N after the ID.