跳到内容

如何使用多个按钮提交表单

编辑此页

当你的表单包含多个提交按钮时,你可能想要检查点击了哪个按钮,以便在控制器中调整程序流程。为此,向你的表单添加第二个标题为 "保存并添加" 的按钮

1
2
3
4
5
6
$form = $this->createFormBuilder($task)
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->add('save', SubmitType::class, ['label' => 'Create Task'])
    ->add('saveAndAdd', SubmitType::class, ['label' => 'Save and Add'])
    ->getForm();

在你的控制器中,使用按钮的 isClicked() 方法来查询是否点击了 "保存并添加" 按钮

1
2
3
4
5
6
7
8
9
if ($form->isSubmitted() && $form->isValid()) {
    // ... perform some action, such as saving the task to the database

    $nextAction = $form->get('saveAndAdd')->isClicked()
        ? 'task_new'
        : 'task_success';

    return $this->redirectToRoute($nextAction);
}

或者你可以使用表单的 getClickedButton() 方法来获取被点击按钮的名称

1
2
3
4
5
6
7
8
9
if ($form->getClickedButton() && 'saveAndAdd' === $form->getClickedButton()->getName()) {
    // ...
}

// when using nested forms, two or more buttons can have the same name;
// in those cases, compare the button objects instead of the button names
if ($form->getClickedButton() === $form->get('saveAndAdd')){
    // ...
}
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本