Soo: 我有两个表/实体文本和组,它们通过多种关系链接。 我有一个表单,用户填写复选框以将文本分配到一个或多个组。 我有一个问题,虽然它给我这个错误
执行' INSERT INTO texte_groupe时发生异常 (texte_id,groupe_id)VALUES(?,?)'与params [2,1]:
这是问题的核心(我认为?)
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); } ); }
由于
答案 0 :(得分:1)
尝试:
foreach ($groupes->toArray() as $groupe) {
if (!in_array($groupe, $texte->getGroupe()->toArray()) {
$texte->addGroupe($groupe);
}
}