0

我有一个具有这种关系的实体“产品”:

/**
 * @var \stdClass
 *
 * @ORM\ManyToMany(targetEntity="ListeBundle\Entity\GarDegatEaux", cascade={"persist"})
 * @ORM\JoinTable(name="produit_garDegatEaux",
 *      joinColumns={@ORM\JoinColumn(name="produit_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="garDegatEaux_id", referencedColumnName="id", unique=false)})
 */
private $garDegatEaux;

如下所示的表单类型:

->add('garDegatEaux', CollectionType::class, array('entry_type' => GarDegatEauxType::class,
                                                           'allow_add' => true,
                                                           'allow_delete' => true,
                                                           //'by_reference' => false,
                                                           'prototype' => true,
                                                           'label' => 'Coefficients dégât des eaux',
                                                           'entry_options' => array('label' => 'Coefficients'),
                                                           'attr' => array('class' => 'collection')
                                                        ))

当通过引用设置为 false 我有这个错误:

属性“garDegatEaux”和方法之一“addGarDegatEau()”/“removeGarDegatEau()”、“setGarDegatEaux()”、“garDegatEaux()”、“__set()”或“__call()”都不存在并且具有公共在“DevisBundle\Entity\Produit”类中访问。

当然在我的实体 addGarDegatEau()"/"removeGarDegatEau()" 和 get.. 存在并拥有公共访问权限。我还有我的构造函数:

$this->garDegatEaux = new \Doctrine\Common\Collections\ArrayCollection();

当“by_reference”设置为 true 时,没有错误,但不会为集合提交任何内容。当我在持久化之前转储表单时,ArrayCollection 中没有任何内容。

并且当“by_reference”被注释时,没有错误,但 ArrayCollection 也没有保留任何内容。

我的控制器:

public function creerProduitAction(Request $request) {

    $produit = new Produit;
    $formProduit = $this->createForm(ProduitType::class, $produit);

    $formProduit->handleRequest($request);

    if ($formProduit->isValid() && $formProduit->isSubmitted()) {



        $em = $this->getDoctrine()->getManager();

        $em->persist($produit);
        $em->flush();
    }

    return $this->render('AdminBundle:Produit:creerProduit.html.twig', array(
        'formProduit' => $formProduit->createView()
    ));
}

我在 symfony 2.7 中使用了 collection,这个过程奏效了。我使用 symfony 2.8 atm。我不明白为什么不保留集合。

4

1 回答 1

0

首先,正如Symfony 的文档所说:

类似地,如果您使用 CollectionType 字段,而您的基础集合数据是一个对象(例如 Doctrine 的 ArrayCollection),那么如果您需要添加器和移除器(例如 addAuthor() 和 removeAuthor()),则必须将 by_reference 设置为 false叫做。

这正是您的情况,因此by_reference应设置为false.

至于你得到的错误,我很确定你不需要getter/setter,尽管你认为你有。请检查他们的名字等是否有任何拼写错误。

于 2016-05-16T13:20:21.577 回答