从 Symfony 2.3 开始你可以:
表格:
$form = $this->createFormBuilder($task)
->add('name', 'text')
->add('save', 'submit')
->add('save_and_add', 'submit')
->getForm();
控制器:
if ($form->isValid()) {
// ... do something
// the save_and_add button was clicked
if ($form->get('save_and_add')->isClicked()) {
// probably redirect to the add page again
}
// redirect to the show page for the just submitted item
}
请参阅此处:http://symfony.com/blog/new-in-symfony-2-3-buttons-support-in-forms
您可以使用例如
$request = $this->get('request');
if ($request->request->has('delete'))
{
...
}
只需在表单生成器中创建按钮,在视图中呈现它们并使用您在其他表单中已使用的相同方法:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('delete', 'button')
->add('print', 'button')
}
您认为:
<form name="" action="{{ path('mypath') }}" method="post">
{{ form_widget(form.print) }}
{{ form_widget(form.delete) }}
...
</form>
Symfony3 更新:
use Symfony\Component\HttpFoundation\Request;
public function myAction(Request $request)
{
if ($request->query->has('delete')) // For GET form
{
// ...
}
if ($request->request->get('delete')) // For POST form
{
// ...
}
}
对于 2023 年,如果其他人遇到此问题,我找到的解决方法如下:
形式:
$form = $this->createFormBuilder()
->add('name', 'text')
->add('save', 'submit')
->add('save_and_add', 'submit')
->getForm();
控制器:
$buttonSave = $form->all()['save']
if ($buttonSave instanceof SubmitButton && $buttonSave->isClicked()) {
//your logic here
}
类似方式
$form->all()['save_and_add']
$form->get('save_and_add')
返回一个 FormInterface
对象,而不是 SubmitButton
,因此,您无权访问 isClicked()
方法