简体   繁体   English

双向关系形式

[英]Bidirectionnal relation in form

i'm having difficulties to save a form that contains a collection from a OneToMany bidirectionnal relation. 我很难保存包含来自OneToMany双向关系的集合的表单。

I got the following error : 我收到以下错误:

An exception occurred while executing 'INSERT INTO fieldsgroup (title, colloque_id) VALUES (?, ?)' with params ["groupe 1", null]:

Here are the queries that the profiler gives me : START TRANSACTION; 这是探查器给我的查询:START TRANSACTION;

INSERT INTO colloque (title)
VALUES
  ('titre du colloque');

INSERT INTO fieldsgroup (title, colloque_id)
VALUES
  ('titre de mon groupe de champs', null)

ROLLBACK    

My controller : 我的控制器:

public function createColloqueAction()
{

  $colloque = new Colloque();   
  $form = $this->createForm(new ColloqueType, $colloque);   

  $request = $this->get('request');   
  if ($request->getMethod() == 'POST'){   
    $form->bind($request);

    if ($form->isValid()) {

      $this->get('session')->getFlashBag()->add('notice', 'Colloque correctement enregistré');

      $em = $this->getDoctrine()->getManager();
      $em->persist($colloque);
      $em->flush();

      return $this->redirect($this->generateUrl('ptolemee_admin_homepage'));
    }   

  }       

  return $this->render('PtolemeeAdminBundle:Admin:createColloque.html.twig',array(
    'form'    =>   $form->createView()                                         
  ));
}

My "Colloque" entity : 我的“ Colloque”实体:

class Colloque
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Ptolemee\ColloqueBundle\Entity\FieldsGroup", mappedBy="colloque", cascade={"persist"})
     */
    private $fieldsGroups; 

    public function __construct()
    {
        $this->fieldsGroups = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add fieldsGroups
     *
     * @param \Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups
     * @return Colloque
     */
    public function addFieldsGroup(\Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups)
    {
        $this->fieldsGroups[] = $fieldsGroups;
        $fieldsGroups->setColloque($this);
        return $this;
    }

    /**
     * Remove fieldsGroups
     *
     * @param \Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups
     */
    public function removeFieldsGroup(\Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups)
    {
        $this->fieldsGroups->removeElement($fieldsGroups);
    }

    /**
     * Get fieldsGroups
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getFieldsGroups()
    {
        return $this->fieldsGroups;
    }
}

Its form, ColloqueType : 其形式为ColloqueType:

class ColloqueType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title',              'text')
            ->add('date',               'datetime')
            ->add('successMessage',     'textarea')
            ->add('fieldsGroups',       'collection',   array(  'type'        =>      new FieldsGroupType(),
                                                                'allow_add'   =>      true,
                                                                'allow_delete'   =>   true))
        ;
    }
}

My class FieldsGroup 我的班级FieldsGroup

class FieldsGroup
{

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**                                                                                  
     * @ORM\ManyToOne(targetEntity="Ptolemee\ColloqueBundle\Entity\Colloque", inversedBy="fieldsGroups")
     * @ORM\JoinColumn(nullable=false)
     */
    private $colloque;

    /**
     * Set colloque
     *
     * @param \Ptolemee\ColloqueBundle\Entity\Colloque $colloque
     * @return FieldsGroup
     */
    public function setColloque(\Ptolemee\ColloqueBundle\Entity\Colloque $colloque)
    {
        $this->colloque = $colloque;

        return $this;
    }

    /**
     * Get colloque
     *
     * @return \Ptolemee\ColloqueBundle\Entity\Colloque
     */
    public function getColloque()
    {
        return $this->colloque;
    }

}

And its form, FieldsGroupType : 其形式为FieldsGroupType:

class FieldsGroupType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title',      'text')
            /*->add('fields',     'collection',   array('type'        =>      new FieldType(),
                                                      'allow_add'   =>      true,
                                                      'allow_delete'   =>      true))*/
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ptolemee\ColloqueBundle\Entity\FieldsGroup'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ptolemee_colloquebundle_fieldsgroup';
    }
}

I know this should work properly without any more perist(), or anything else... Any help would be highly appreciated, i've been working on that for hours without finding what's the right way to do.... 我知道这应该在没有更多的perist()或其他任何东西的情况下可以正常工作...任何帮助将不胜感激,我已经花了好几个小时没有找到正确的方法去做...。

Thanks a lot ! 非常感谢 !

Just add setFieldsGroup(ArrayCollection) to your entity 只需将setFieldsGroup(ArrayCollection)添加到您的实体

     public function addFieldsGroup(\Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups)
        {
           $this->fieldsGroups[] = $fieldsGroups;
           $fieldsGroups->setColloque($this);
           return $this;
        }

    public function setFieldsGroup(ArrayCollection $fieldsGroups)
       {
           foreach ($fieldsGroups as $fieldsGroup) {
               $fieldsGroup->setColloque($this);
           }
           $this->fieldsGroups = $fieldsGroups;
       }

Adding setFieldsGroup(ArrayCollection) is working but it's a trick. 添加setFieldsGroup(ArrayCollection)是可行的,但这是一个技巧。

Simply add , cascade={"persist"} to your ManyToOne field 只需在您的ManyToOne字段中添加, cascade={"persist"}

/**                                                                                  
 * @ORM\ManyToOne(targetEntity="Ptolemee\ColloqueBundle\Entity\Colloque", inversedBy="fieldsGroups", cascade={"persist"})
 * @ORM\JoinColumn(nullable=false)
 */
private $colloque;

PS1 : Prefer handleRequest() instead of $request->getMethod() == 'POST' and $form->bind($request) if you have Symfony2.x x>=3. PS1:如果您有Symfony2.x x> = 3,则首选handleRequest()代替$request->getMethod() == 'POST'$form->bind($request)

PS2 : You can get request like this when needed (more elegant way) : PS2:您可以在需要时收到这样的请求(更优雅的方式):

public function createColloqueAction(Request $request)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM