How can I have optional parameters in Symfony2 route?

69,381

Solution 1

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)
{

Solution 2

Use a yml file for your routing configuration, and add a default value for id in your routing parameters like this:

user:
  pattern:   /site/user/{id}
  defaults:  { _controller: YourBundle:Default:index, id: 1 }

See documentation here

Solution 3

You could also do it with a GET parameter, e.g.

/**
 * @param Request $request
 *
 * @return Response
 */
public function displayDetailAction(Request $request) : Response
{
    if ($courseId = $request->query->get('courseId')) {
Share:
69,381

Related videos on Youtube

Mirage
Author by

Mirage

Updated on July 09, 2022

Comments

  • Mirage
    Mirage almost 2 years

    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?

  • phpguru
    phpguru over 8 years
    The OP is obviously using route annotations in the controller
  • Andrew
    Andrew almost 8 years
    Yet his answer helped me and a few others
  • Jazi
    Jazi over 7 years
    Notice for future: pattern key is deprecated in Symfony 3
  • Delphine
    Delphine about 7 years
    ... and you have to use path key instead (SF3)
  • Gangai Johann
    Gangai Johann over 6 years
    According to the best practices, should be the correct answer.
  • Azhar Khattak
    Azhar Khattak about 6 years
    Awesome, Thanks!
  • DevLime
    DevLime almost 6 years
    It was only a problem for a very short amount of time, but setting a default value on the parameter ($cid in this case) - very important :p