简体   繁体   中英

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?

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, ie

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

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

You could also do it with a GET parameter, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM