Forms 带有两个提交按钮的Symfony 2表单
因此,我有一个表,每行都有一个复选框,如下所示:Forms 带有两个提交按钮的Symfony 2表单,forms,symfony,button,Forms,Symfony,Button,因此,我有一个表,每行都有一个复选框,如下所示: <form name="" action={{ path('mypath') }}" method="post"> <button name="print">Print</button> <button name="delete">Delete</button> <table> {% for client in clienti %} <tr>
<form name="" action={{ path('mypath') }}" method="post">
<button name="print">Print</button>
<button name="delete">Delete</button>
<table>
{% for client in clienti %}
<tr>
<td><input type="checkbox" name="action[]" value="{{ client.id }}" /></td>
</tr>
.
.
.
{% endfor %}
</table>
</form>
我想知道做这件事的正确方法
谢谢。您可以使用
$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>
{{form_小部件(form.print)}
{{form_小部件(form.delete)}
...
自Symfony 2.3以来,您可以执行以下操作:
表格:
控制器:
请参见此处: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
{
// ...
}
}
你的答案很好,但我没有表单生成器,所以我需要一种更简单的方法来实现这一点。非常感谢您的时间。我会投票支持您,但我不能,我只有14个代表点。我理解:)只要尽可能在应用程序中使用适当的表单,从长远来看,这将为您省去麻烦!更通用的方法是
$request->request->has('delete')
,因为表单可以发布数据。
$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
}
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
{
// ...
}
}