Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have optional parameters in Symfony2 route?

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?

like image 276
Mirage Avatar asked Aug 16 '12 03:08

Mirage


People also ask

Is a optional parameter in URL?

Parameters provide a way of passing arbitrary data to a page via the URL. Optional parameters allow URLs to matched to routes even if no parameter value is passed. Things can get a bit complicated if you want to permit multiple optional parameters.

What is route in Symfony?

When your application receives a request, it calls a controller action to generate the response. The routing configuration defines which action to run for each incoming URL. It also provides other useful features, like generating SEO-friendly URLs (e.g. /read/intro-to-symfony instead of index.


2 Answers

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) { 
like image 88
Inoryy Avatar answered Sep 28 '22 03:09

Inoryy


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

like image 33
fkoessler Avatar answered Sep 28 '22 03:09

fkoessler