Customer
is the inverse side of "keywords/customers" relationship with Keyword
:
/**
* @ORM\ManyToMany(targetEntity="Keyword", mappedBy="customers",
* cascade={"persist", "remove"}
* )
*/
protected $keywords;
When creating a new customer, one should select one or more keywords. The entity form field is:
$form->add($this->factory->createNamed('entity', 'keywords', null, array(
'class' => 'Acme\HelloBundle\Entity\Keyword',
'property' => 'select_label',
'multiple' => true,
'expanded' => true,
)));
In my controller code, after binding the request and check if form is valid, I need to persist both the customer and all customer/keyword(s) associations, that is the join table.
However customer is the inverse side, so this is not working:
if($request->isPost()) {
$form->bindRequest($request);
if(!$form->isValid()) {
return array('form' => $form->createView());
}
// Valid form here
$em = $this->getEntityManager();
$em->persist($customer);
$em->flush();
}
Event with "cascade" option, this code fails. $customer->getKeywords()
will return Doctrine\ORM\PersistentCollection
, which holds only selected keywords.
Should I manually check which keyword was removed/added and then update from the owning side?