How to disable soft delete (Soft-deleteable) filter for doctrine in symfony

Aurelijus Rozenas picture Aurelijus Rozenas · Jul 5, 2016 · Viewed 15.6k times · Source

Installing and using SoftDeleteable behavior extension for Doctrine 2 is quite easy. The problem usually is trying to disable it for some code part and enabling again. You may want to do this to:

  1. load entity that is soft-deleted
  2. remove entity from database entirely bypassing soft-delete filter

So how to disable it?

Answer

Aurelijus Rozenas picture Aurelijus Rozenas · Jul 5, 2016

1. How to load soft-deleted entity

As per the documentation, disable filter for entity manager:

$em->getFilters()->disable('softdeleteable');
$object = $em->find('AppBundle:Object', 1); // soft-deleted entity will be loaded

To enable soft-delete again:

$em->getFilters()->enable('softdeleteable');

Note: $em->clear(); may be required before this line, if entity was already loaded with disabled soft-delete filter.

2. How to remove entity from database entirely

Even though it is not mentioned in documentation, the first solution does not work if you need to remove entity and bypass soft-delete filter. Filter needs to be removed from entity manager's event listeners:

// initiate an array for the removed listeners
$originalEventListeners = [];

// cycle through all registered event listeners
foreach ($em->getEventManager()->getListeners() as $eventName => $listeners) {
    foreach ($listeners as $listener) {
        if ($listener instanceof \Gedmo\SoftDeleteable\SoftDeleteableListener) {

            // 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($object);
$em->flush($object); // or $em->flush();

// re-add the removed listener back to the event-manager
foreach ($originalEventListeners as $eventName => $listener) {
    $em->getEventManager()->addEventListener($eventName, $listener);
}

References: