I have a ManyToMany relationship between two entities (ClientProject & Tour) that is actually working except from one case. When I want to clear all relations between those entities, it doesn't work and the database is not updated accordingly.
ClientProject.php
/**
* @ORM\ManyToMany(targetEntity="Tour", inversedBy="clientProjects")
* @ORM\JoinTable(
* name="client_projects_tour_items",
* joinColumns={
* @ORM\JoinColumn(name="client_project_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="tour_id", referencedColumnName="id")
* }
* )
*/
protected $tourItems;
public function removeTourItem(\SharedBundle\Entity\Tour $tourItem)
{
$this->tourItems->removeElement($tourItem);
}
Tour.php
public function removeClientProject(\SharedBundle\Entity\ClientProject $clientProject)
{
$this->clientProjects->removeElement($clientProject);
}
Working example:
- Before update:
- Tour 1 / ClientProject 3
- Tour 1 / ClientProject 4
- Action: remove relation between Tour 1 and ClientProject 4
- After update:
- Tour 1 / ClientProject 3
Failing example:
- Before update:
- Tour 1 / ClientProject 3
- Action: remove relation between Tour 1 and ClientProject 3
- After update:
- Tour 1 / ClientProject 3
Controller action
public function editClientProjectAction($id, Request $request)
{
if (!$request->isXmlHttpRequest()) {
return $this->redirectToRoute('contact');
}
$clientProject = $this->getDoctrine()->getRepository(ClientProject::class)->find($id);
if(!$clientProject) {
return new JsonResponse(array('redirect' => $this->generateUrl('contacts')));
}
$form = $this->createForm(ClientProjectFormType::class, $clientProject, array(
'action' => $this->generateUrl('edit-client-project', array('id' => $id))
));
$form->setData($clientProject);
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()), false);
if($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($clientProject);
$em->flush();
return new JsonResponse(array('reloadDatatable' => 'client_project_datatable'));
} else {
return new JsonResponse(array('reload' => true));
}
}
return $this->render('@AppBundle/client-projects/edit-client-project.html.twig', [
'form' => $form->createView(),
]);
}