php 我如何在 Symfony2 路由中有可选参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11980175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i have optional parameters in Symfony2 route
提问by Mirage
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/1then it works, but if I type site/user/it says:
现在,如果我输入,site/user/1那么它可以工作,但是如果我输入site/user/它,它会说:
No route found
How can I have it that both routes work?
我怎么能知道两条路线都有效?
回答by Inoryy
Try to go to site/user(notice no backslash at the end).
尝试转到site/user(注意末尾没有反斜杠)。
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)
{
回答by fkoessler
回答by crmpicco
You could also do it with a GET parameter, e.g.
你也可以用一个 GET 参数来做,例如
/**
* @param Request $request
*
* @return Response
*/
public function displayDetailAction(Request $request) : Response
{
if ($courseId = $request->query->get('courseId')) {

