【问题标题】:symfony2: change url route parameter with a formsymfony2:使用表单更改 url 路由参数
【发布时间】:2016-07-06 11:49:28
【问题描述】:

我需要能够让用户在应用程序中选择一些参数。所以我创建了一个表单,让用户例如选择一年。

我将表单的操作更改为GET,并将其name 更改为null。提交表单时,这会在 url 中添加一个经典的 url-query-string-parameter。

但是我正在使用 symfony-routes,我想让提交表单的结果更改路由参数。

为了清楚起见,这是一个示例:假设我会使用这样的路线:

@Route("/assignment/{year}", name="assignment")
function indexAction($year){...}

然后我想通过提交这样的表格来更改年份路线参数。

$this->get('form.factory').createNamedBuilder(null, FormType::class)
  ->setAction('get')
  ->add('year', ChoiceType::class, ['choices' => [2016 => 2016, 2022 => 2022]])
  ->add('submit', SubmitType::class);

有没有办法在不添加额外 javascript 的情况下存档? 如果无法存档,最好的选择是什么?删除路由参数并“手动”处理表单数据?

【问题讨论】:

  • 为什么需要一个表格?除非您有超过 1 个参数,否则最好使用下拉菜单 ala Bootstrap 并为每个 a 元素添加具有适当年份的链接。

标签: php forms symfony


【解决方案1】:

如果表单也在/assignment/{year} 路由上,那么这可能是一个想法。

indexAction()函数中,可以查看表单是否已经提交,如果是,则重定向回表单中选择年份的路由。

//SomethingController.php
public function indexAction($year, Request $request)
{
    //...
    $form = $this->get('form.factory'). // You know the rest

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        // Do some stuff depending on values of form if you'd like, and then

        $this->redirectToRoute('assignment', ['year' => $year]);
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-11
    • 2016-09-15
    • 2021-06-03
    • 2015-10-02
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多