0
votes

In symfony2 routing.yml I am trying to create a route with optional parameters like this:

/app/type/{typeValue}/page/{page}

So, an example that would work is:

/app/test/type/hello/page/1

My route is:

api_test:
    pattern:   /api/test/type/{typeValue}/page/{page}
    defaults: { _controller: TestCoreBundle:Json:test, page:1 }    

This is fine but i want to have /type/{typeValue} and /page/{page} optional so it works also for urls like this:

/app/test
/app/test/page/3
/app/test/type/myType

My other routes will also contain more complicated optional parameters so it is important for me to solve this problem. What do I need to do so that I dont need to create separate routes so it supports every single combination?

2

2 Answers

0
votes

Dynamic routing params still need to be filled or defaulted, I would recommend passing these as options then append to a query string such as ?page=1&myType=blah and use $request->get() in your controller, base class.

0
votes

As explained on the symfony page everything after an optional placeholder has to be optional too.

Of course, you can have more than one optional placeholder (e.g. /blog/{slug}/{page}), but everything after an optional placeholder must be optional. For example, /{page}/blog is a valid path, but page will always be required (i.e. simply /blog will not match this route).

In your case {typeValue} is optional but followed by /page/ which is not optional, so this rout will never work with both parameters optional. You can either use query strings or change your route to something like

api_test:
    pattern:   /api/test/{typeValue}/{page}
    defaults: { _controller: TestCoreBundle:Json:test, typeValue: 'default', page: 1 }
    requirements:
        page:  \d+

You will then be able to use routes

/app/test
/app/test/myType
/app/test/myType/3

But even then route /app/test/3 is not possible, since symfony will interpret this as $typeValue = 3 and $page as default.