Force Doctrine Object Deletion Using SoftDeletable by KnpLabs

I use the SoftDeletable property in objects from https://github.com/KnpLabs/DoctrineBehaviors/#softDeletable It works fine, but sometimes I would like to force the object to be deleted. How can i do this?

When I use $em->remove($entity) , it gets soft-deleted, but I need to completely remove it from the database.

+1
symfony entity-framework doctrine2
source share
3 answers

Just remove the subscriber from the EventManager and add it after the remove() / flush() operation.

 // get the event-manager $eventManager = $this->get('doctrine')->getEventManager(); // get the listener $subscriber = $this->get('knp.doctrine_behaviors.softdeletable_subscriber'); // remove the the subscriber for all events $eventManager->removeEventListener($subscriber->getSubscribedEvents(), $subscriber); // remove the entity $em->remove($entity); $em->flush(); // add it back to the event-manager $eventManager->addEventSubscriber($subscriber); 
+2
source share

Since nifr's answer no longer works in the current version of the behavior, I looked deeper into the problem and got to this solution:

 $em = $this->getDoctrine()->getManager(); // initiate an array for the removed listeners $originalEventListeners = array(); // cycle through all registered event listeners foreach ($em->getEventManager()->getListeners() as $eventName => $listeners) { foreach ($listeners as $listener) { if ($listener instanceof Knp\DoctrineBehaviors\ORM\SoftDeletable\SoftDeletableSubscriber) { // store the event listener, that gets removed $originalEventListeners[$eventName] = $listener; // remove the SoftDeletableSubscriber event listener $em->getEventManager()->removeEventListener($eventName, $listener); } } } // remove the entity $em->remove($entity); $em->flush(); // re-add the removed listener back to the event-manager foreach ($originalEventListeners as $eventName => $listener) { $em->getEventManager()->addEventListener($eventName, $listener); } 

See also stack overflow.

+2
source share

I found a simple solution. At first, the object will be softdeletes, but if it has already been deleted, it will be deleted, so my simple solution:

 $entity->setDeletedAt(new DateTime()); $entityManager->remove($entity); $entityManager->flush(); 

Of course, you need to turn off the softdelete filter first, and deletedAt the sofdelete field.

0
source share

All Articles