gpt4 book ai didi

symfony - 表单的 View 数据应该是 MyEntity 的实例,但却是 ArrayCollection 的实例

转载 作者:行者123 更新时间:2023-12-02 10:00:38 27 4
gpt4 key购买 nike

我可以创建一个工作正常但在尝试将数据刷新到数据库时出现错误的表单:

Controller 操作如下所示:

$purchase = new Purchase();
$form = $this->createFormBuilder($purchase)
->add('addresses', AddressType::class)
->add('quantity', IntegerType::class)
->add('toBeDeliveredAt', DateType::class)
->add('comment', TextareaType::class)
->add('save', SubmitType::class, array('label' => 'Submit'))
->getForm();

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($purchase);
$em->flush();
}

类 AddressType 如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)

{
$builder
->add('title', TextType::class)
->add('firstname', TextType::class)
->add('lastname', TextType::class)
->add('street', TextType::class)
->add('city', TextType::class)
->add('zipcode', TextType::class)
->add('country', TextType::class)
->add('phone', TextType::class)
->add('email', EmailType::class);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'XxxBundle\Entity\Address'
));
}

但这给了我以下错误:

The form's view data is expected to be an instance of class XxxBundle\Entity\Address, but is an instance of class Doctrine\Common\Collections\ArrayCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\Common\Collections\ArrayCollection to an instance of XxxBundle\Entity\Address.

如果我将 data_class 选项设置为 null,我会得到

Warning: spl_object_hash() expects parameter 1 to be object, string given

如何添加一个 View 转换器,将 ArrayCollection 类的实例转换为 Address 的实例?

最佳答案

Addresses 是一个数组集合,因此您必须将其用作表单中的集合,如下所示:

$builder->add('addresses', CollectionType::class, array(
'entry_type' => AddressType::class
));

而不是这个:

$builder->add('addresses', AddressType::class)

通过这种方式,您可以将地址表单嵌入到购买表单中

您可以查看有关嵌入 here 形式的集合的文档

解释(抱歉我的英语不好):

你必须考虑对象。

在您的购买实体中,您有一个地址集合,因为购买对象可以有许多地址,也就是说要持久保存购买对象,您必须提供地址集合。

因此,当您构建 Purshase 表单时,Symfony 需要一个用于地址输入的数组集合。这是我上面写的。这样,如果您想要添加新的购买对象,当您查看表单时,要显示与地址对应的字段,您必须在表单中执行以下操作:

    <ul class="addresses">
{# iterate over each existing address and render these fields #}
{% for address in form.addresses %}
<li>{{ form_row(address.title) }}</li>

//do this for all the others fields ...

{% endfor %}
</ul>

但是如果你想动态添加许多地址,你必须做两件事:

首先,您必须在表单构建器中添加 'allow_add' => true

$builder->add('addresses', CollectionType::class, array(
'entry_type' => AddressType::class,
'allow_add' => true,
));

其次,allow_add 还以生成的 html 形式提供了一个“原型(prototype)”变量:这就是 Javascript 的用武之地:)要做到这一点,您必须编写一些 Javascript,您可以看到一个很好的示例 here

我希望它更清楚

关于symfony - 表单的 View 数据应该是 MyEntity 的实例,但却是 ArrayCollection 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611961/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com