I have problem with the array collection.
If i don't use "$livraison->setChoix($livraison->getChoix());" in form valid, the item is doesn't save in relation. And with this, the item in collection as duplicate in any save.
i have 2 entity, "Livraison" and "LivraisonChoix"
Livraison is in relation OneToMany with LivraisonChoix LivraisonChoix is in relation ManyToOne with Livraison
this is the Livraison :
...
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
class Livraison
{
...
/**
* @ORM\OneToMany(targetEntity="\YOU\CommercantBundle\Entity\LivraisonChoix", mappedBy="livraison", cascade={"all"})
**/
private $choix;
public function __construct()
{
$this->choix = new ArrayCollection();
}
public function addChoix(\YOU\CommercantBundle\Entity\LivraisonChoix $choix)
{
$choix->setLivraison($this);
$this->choix[] = $choix;
}
public function setChoix($choix)
{
foreach($choix as $choi){
$this->addChoix($choi);
}
}
public function removeChoix($choix)
{
$this->choix->removeElement($choix);
}
public function getChoix()
{
return $this->choix;
}
...
this is the LivraisonChoix :
use Doctrine\ORM\Mapping as ORM;
class LivraisonChoix
{
...
/**
* @ORM\ManyToOne(targetEntity="YOU\CommercantBundle\Entity\Livraison", inversedBy="choix")
**/
private $livraison;
...
public function setLivraison($livraison)
{
$this->livraison = $livraison;
return $this;
}
public function getLivraison()
{
return $this->livraison;
}
...
this is the form builder :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('choix','collection',array(
'type'=>new LivraisonChoixType(),
'allow_add' => true,
'allow_delete' => true,
))
;
}
And this is the controller :
$livraison = new Livraison();
$form = $this->createForm(new LivraisonType(), $livraison);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$livraison->setAccount($customer);
$livraison->setChoix($livraison->getChoix());
$em->persist($livraison);
$em->flush();
return $this->redirect($this->generateUrl('you_commercant_livraison_editer',array('id'=>$livraison->getId())));
}
}