How can i have optional parameters in Symfony2 route

Mirage picture Mirage · Aug 16, 2012 · Viewed 63.8k times · Source

I have this code below :

/**
 * Lists all User entities.
 *
 * @Route("/{cid}",defaults={"cid" = null},name="user")
 * @Template()
 */
public function indexAction($cid=null)
{}

Now if I type site/user/1 then it works, but if I type site/user/ it says:

No route found

How can I have it that both routes work?

Answer

Inoryy picture Inoryy · Aug 16, 2012

Try to go to site/user (notice no backslash at the end).

Generally it should work, I have relatively similar configuration working.

But if all else fails you can always define multiple routes for same action, i.e.

/**
 * Lists all User entities.
 *
 * @Route("/", name="user_no_cid")
 * @Route("/{cid}", name="user")
 * @Template()
 */
public function indexAction($cid=null)
{