I am having issues saving the selections made in a entity form field with multiple=true.
The selections come through when $form->bindRequest($request) is called but don’t persist in the database when flush is called.
Here is the relevant controller code:
$news_item = new News();
$form = $this->createFormBuilder($news_item)
->add('products', 'entity',
array('class' => 'AcmeDemoBundle:Product',
'multiple' => TRUE))
->getForm();
$request = $this->getRequest();
if($request->getMethod() == "POST") {
$form->bindRequest($request);
if($form->isValid()) {
$this->em->persist($news_item);
$this->em->flush();
}
}
I have checked the $news_item object after $form->isValid() and a count($news_item->getProducts()) returns the correct number of items. The $news_item itself is saved in the DB but the ManyToMany relationship isn’t being saved.
Here are the entities for reference (clipped for brevity):
/**
* @ORM\Entity
* @ORM\Table(name="Product")
*/
class Product {
/*
* @ORM\Id @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\ManyToMany(targetEntity="News", inversedBy="products")
*/
protected $news_items = null;
public function __construct() {
$this->news_items = new ArrayCollection();
}
}
/**
* @ORM\Entity
* @ORM\Table(name="News")
*/
class News {
/**
* @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\ManyToMany(targetEntity="Product", mappedBy="news_items")
*/
protected $products = null;
public function __construct() {
$this->products = new ArrayCollection();
}
}
I think you are missing
$product->addNewsItem($news_item)and$news_item->addProduct($product)in your code this because in bi-directional associations (seems your case) you have to update the fields on both sides.To avoid this you can set the cascade option on both sides of the association:
This way your code will work. You can choose the appropriate cascade options looking at here.