I have two entities : Product and Picture with a one-to-many relation. I try to create a product form with a pictures collection. I can edit my product and all its pictures. To add a new one, I create new fields with javascript.
The problem is that when I submit the form, new pictures are persisted without a product_id, and an exception is thrown.
What am I doing wrong ? Here is my code :
Product class
- Code: Select all
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Picture", mappedBy="product", cascade={"all"})
*/
protected $pictures;
Picture class
- Code: Select all
/**
* @var Product $product
*
* @ORM\ManyToOne(targetEntity="Product", inversedBy="pictures")
* @ORM\JoinColumn(nullable=false)
*/
protected $product;
Form (in my action)
- Code: Select all
$product = $this->getRepository()->find(1);
$form = $this->createFormBuilder($product)
->add('title', 'text')
->add('pictures', 'collection', array(
'type' => new PictureType(),
'allow_add' => true,
'prototype' => true,
))
->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($product);
$em->flush();
}
}
