I am posting an array of entities to a controller, all of which I\'d like to delete. However, the below code throws an A detached entity was found during removed MyProject
You should use merge operation on entities which are in detached state and you want to put them to managed state.
Merging should be done like this $entity = $em->merge($detachedEntity)
. After that $entity
refers to the fully managed copy returned by the merge operation. Therefore if your $form
contains detached entities, you should adjust your code like this:
$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $detachedEntity) {
$entity = $doctrineManager->merge($detachedEntity);
$doctrineManager->remove($entity);
}
$doctrineManager->flush();
However, in case that the $form
does not contain detached entities, you should remove the merge operation, like this:
$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $entity) {
$doctrineManager->remove($entity);
}
$doctrineManager->flush();
This image should help you to understand entity state transitions. It is taken from Java Persistence API, but in Doctrine2 it is about the same.