Search code examples
formssymfonydoctrinemany-to-many

ManyToMany, duplicate entry, table empty


Soo : I have my two tables/entities texts and groups which are linked by a manytomany relationship. I have a form where the users fill checkboxes to assign a text into one or several groups. I have a problem though it's getting me this error

An exception occurred while executing 'INSERT INTO texte_groupe (texte_id, groupe_id) VALUES (?, ?)' with params [2, 1]:

Here is the core of the problem ( i think?)

public function AcceptMediaAction($id)    {
    $em = $this->getDoctrine()->getManager(); 

    $texte = new Texte();
    $securityContext = $this->container->get('security.context');
    $texte = $em->getRepository('EVeilleurDefuntBundle:Texte')->find($id);
    $form = $this->createForm( new ChooseGroupeType($securityContext), $texte );


    $request = $this->get('request');
    $form->bind($request);

    if ($request->getMethod() == 'POST') {

           $groupes = $texte->getGroupes();
           $statut = $texte->getStatut();

           foreach ($groupes->toArray() as $groupe)
          {
              $texte->addGroupe($groupe);
            }

          $em->persist($groupe);
          $em->flush();
          return $this->redirect($this->generateUrl('e_veilleur_defunt_gerer_medias',

Groupe.php

   /**
     * @ORM\ManyToMany(targetEntity="EVeilleur\DefuntBundle\Entity\Texte",mappedBy="groupes")
     */
     private $textes;

Texte.php

  /**
     * @ORM\ManyToMany(targetEntity="EVeilleur\DefuntBundle\Entity\Groupe",inversedBy="textes")
     */
     private $groupes;

formtype

 public function buildForm(FormBuilderInterface $builder, array
 $options)
{
     // $builder->add('statut','choice', array('choices'=> array('nonValide'=>'non Valide',
     //                                                        'Valilde'=>'suchValidation'),
     //                                        'required'=>'true'
     //                                        )
     //               ) ;     //  , array("attr" => array("multiple" => "multiple",  ))


    $user = $this->securityContext->getToken()->getUser();
    if (!$user) {
        throw new \LogicException(
            'This cannot be used without an authenticated user!'
        );
    }

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($user) {
            $form = $event->getForm();

            $formOptions = array(
                'multiple' => true, //several choices
                'expanded' => true, // activate checkbox instead of list
                'by_reference' => false,
                'required' => true|false,
                'class' => 'EVeilleur\DefuntBundle\Entity\Groupe',
                'query_builder' => function (EntityRepository $er) use ($user) {
                    // build a custom query
                    return $er->createQueryBuilder('u')->add('select', 'u')
                                                       ->add('from', 'EVeilleurDefuntBundle:Groupe u');
                                                     //  ->add('where', 'u.id = ?1')
                                                     //  ->add('orderBy', 'u.name ASC');

                },
            );

            // create the field, = $builder->add()
            // field name, field type, data, options
            $form->add('groupes', 'entity', $formOptions);
        }
    );

}

Thanks


Solution

  • Try with:

    foreach ($groupes->toArray() as $groupe) {
        if (!in_array($groupe, $texte->getGroupe()->toArray()) {
            $texte->addGroupe($groupe);
        }
    }