Symfony3 多次渲染相同的表单 [英] Symfony3 Render multiple time same form
问题描述
我想多次呈现同一个表单来处理两个不同选项卡的相同操作.问题是当我尝试时,只显示第一个选项卡的表单,如果我更改表单的 id 和 name.我发现这是 symfony 的预期行为,但我仍然需要它来工作.
I would like to render the same form multiple times to handle the same action for two different tabs. The problem is that when I try, only the form of the first tab is shown, event if I change the id and name of the form. I found out it's the expected behavior of symfony, but I still need it to work.
我发现它可能适用于集合,但不知道它是如何工作的.
I found that it may works with a collection but don't get how it would work.
树枝:
{{ form(contactForm, {'attr': {'id': 'contactFormId' ~ Client.Id}, 'name': "contactFormName" ~ Client.Id})}}
表格:
$this->contactForm = $this->createFormBuilder($contact, array('allow_extra_fields' =>true))
->add('Nom', TextType::class, array('mapped'=>false))
->add('Prenom', TextType::class, array('mapped'=>false))
->add('Telephone', TextType::class, array(
'label' => 'Téléphone'))
->add('Email', TextType::class)
->add('Ajouter', SubmitType::class)
->getForm();
推荐答案
这是一个较老的问题,但我只是遇到了类似的情况.我想在列表视图中有一个表单对象的多个版本.对我来说,解决方案是将表单对象上的 createView()
调用移动到视图,而不是在控制器中调用它.这是一种关于关注点分离的肮脏解决方案,但我想发布它以便它可以帮助其他人.
It is an older question, but I just came across it facing a similar situation. I wanted to have multiple versions of one form object in a list view. For me the solution was to move the createView()
call on the form object to the view instead of calling it in the controller. This is kind of a dirty solution regarding separation of concerns, but I thought to post it so it may help others anyway.
我的控制器动作如下所示:
My controller action looks like this:
/**
* @Route("", name="cart_show")
* @Method("GET")
*/
public function showAction(Request $request)
{
/** @var CartInterface $cart */
$cart = $this->get('rodacker.cart');
$deleteForm = $this->createDeleteForm();
return $this->render(
'AppBundle:Cart:show.html.twig',
['cart' => $cart, 'deleteForm' => $deleteForm]
);
// ...
private function createDeleteForm()
{
return $this->createForm(
OrderItemDeleteType::class,
null,
[
'action' => $this->generateUrl('cart_remove_item'),
'method' => 'DELETE',
]
);
}
}
在视图中,我通过调用控制器传递的表单变量 (deleteForm
) 上的 createView
函数来设置 form
变量:
and in the view I set the form
variable by calling the createView
function on the form variable (deleteForm
) passed from the controller:
{% for item in items %}
{% set form = deleteForm.createView %}
{{ form_start(form) }}
{{ form_widget(form.item, {'value': item.image.filename}) }}
<button type="submit" class="btn btn-xs btn-danger" title="Artikel entfernen">
<i class="fa fa-trash-o"></i> entfernen
</button>
{{ form_end(form) }}
{% endfor %}
这篇关于Symfony3 多次渲染相同的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!