47

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?

peterh
  • 11,875
  • 18
  • 85
  • 108
Mirage
  • 30,868
  • 62
  • 166
  • 261

3 Answers3

80

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)
{
martin
  • 93,354
  • 25
  • 191
  • 226
Inoryy
  • 8,365
  • 2
  • 39
  • 40
39

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

fkoessler
  • 6,932
  • 11
  • 60
  • 92
7

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')) {
crmpicco
  • 16,605
  • 26
  • 134
  • 210