【问题标题】:Symfony2 route in annotations with optional parameters带有可选参数的注释中的 Symfony2 路由
【发布时间】:2013-09-09 08:17:16
【问题描述】:

我在控制器中创建了一个带有可选参数的路由,如下所示:

/**
 * League action
 *
 * @Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
 * @Route("/association/{assoc}/{league}/{game}")
 * @Template()
 *
 * @param $assoc
 * @param $league
 * @param $game
 * @return array
 */
 public function leagueAction($assoc, $league, $game)

但如果我尝试使用此命名路由创建链接,则省略可选参数:

{{ path('league', {'assoc': association.short, 'league': league.id, 'game': g.id}) }}

结果链接是

/association/BVNR/7

我错过了什么?

【问题讨论】:

    标签: symfony annotations router


    【解决方案1】:

    在以下定义中,

    * @Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
    * @Route("/association/{assoc}/{league}/{game}")
    

    两条路线与您的操作有关,第一条路线(名为"league",没有任何默认参数,第二条未命名路线(因为您没有添加名称属性)也没有任何默认值参数。

    如何解决...

    • name 添加到您的第二条路由并调用它,因为它包含"game" 参数。
    • "game" 参数的默认值移动到您的第二条路由(因为它是唯一一个有game 参数的路由。
    • (你真的不需要定义两条路线,看看我回答的"How to improve ..."部分)。

    试试这个...

     * @Route("/association/{assoc}/{league}/{game}", name="league_game", requirements={"league" = "\d+"}, defaults={"game" = null})
    

    虽然您应该调用 "league_game" 而不是 "league"

    {{ path('league_game', {'assoc': association.short, 'league': league.id, 'game': g.id}) }}
    

    如何改进...

    确保您确实需要定义两条路线,因为我建议只保留一条路线。

    因为在下面的定义中有"game"的默认值,

    @Route("/association/{assoc}/{league}/{game}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null}
    

    然后它涵盖两个版本,有和没有"game"

    【讨论】:

    • 啊 - 命名第二条路线就行了。但是我也必须在第一条路线上使用默认值,因为 symfony 声称需要参数游戏。所以这似乎有效:* @Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null }) * @Route("/association/{assoc}/{league}/{game}", name="leaguedetails", defaults={"game" = null})
    • 省略第一条路线不起作用,我尝试了所有组合。
    • 您不需要将“game”定义为第一个路由的默认参数,因为它不包含任何“game”参数。然后,您的第一条路线应按如下方式调用: {{ path('league', {'assoc': association.short, 'league': League.id}) }} 其中 League.id 必须适合 "\d+"约束。
    • Ahmed - 如果我在第一条路线上忽略默认值,我会收到以下错误:控制器“...\LigaController::leagueAction()”要求您为“$game”参数提供一个值(因为没有默认值或者因为在这个之后有一个非可选参数)。虽然在为第一条路线生成链接时我不使用参数游戏。
    • 对不起,你是对的,我没有看到你的动作签名。您需要为leagueAction 使用的所有参数设置一个值(默认或不)。
    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多