Conjugate behavior and indeed deletion of an object

I use DoctrineExtensions with the StofDoctrineExtensionsBundle to get a soft delete.

It works great in the interface of my application.

In the backend, I need the option of β€œhard” deleting objects.

I disabled the filter in my admin controllers (I use SonataAdmin):

$filters = $this->getModelManager()->getEntityManager($this->getClass())->getFilters(); if (array_key_exists('softdeleteable', $filters->getEnabledFilters())) { $filters->disable('softdeleteable'); } 

This works (soft deleted objects appear in the lists), but when I try to delete it, the object becomes soft again. How can I force delete "?"

+7
source share
4 answers

You do not need to turn off the filter - it is simply used to filter records when selected. Instead, you should disable the listener:

 // $em is your EntityManager foreach ($em->getEventManager()->getListeners() as $eventName => $listeners) { foreach ($listeners as $listener) { if ($listener instanceof \Gedmo\SoftDeleteable\SoftDeleteableListener) { $em->getEventManager()->removeEventListener($eventName, $listener); } } } 

and then call

 $em->remove($entity); $em->flush(); 
+10
source

No need to create a listener or anything for HARD delete with softdeleteable enabled.

The original softdelete event has the following line:

 $reflProp = $meta->getReflectionProperty($config['fieldName']); $oldValue = $reflProp->getValue($object); if ($oldValue instanceof \Datetime) { continue; // want to hard delete } 

All this means if you:

 $entity->setDeletedAt(new \Datetime()); $em->flush(); 

And then:

 $em->remove($entity); $em->flush(); 

At this point, it will be deleted.

If you already have a valid date inside the deletedAt field when you call β†’ flush () after a β†’ remove ($ entity), your entity will be hard deleted.

+4
source

Not the most elegant way: you can always do a real deletion using SQL, it will bypass softdeletable

 $em->createQuery("DELETE MyEntity e WHERE e = :et")->setParameter('et',$entity)->execute(); 
+2
source

Although this question is a bit old, it may be useful to someone:

Creating your own event listener might be the best solution:

 class SoftDeleteableListener extends BaseSoftDeleteableListener { /** * @inheritdoc */ public function onFlush(EventArgs $args) { $ea = $this->getEventAdapter($args); $om = $ea->getObjectManager(); //return from event listener if you disabled filter: $em->getFilters()->disable('softdeleteable'); if (!$om->getFilters()->isEnabled('softdeleteable')) { return; } parent::onFlush($args); } } 

And adding to your configuration:

 gedmo.listener.softdeleteable: class: AppBundle\EventListener\SoftDeleteableListener tags: - { name: doctrine.event_subscriber, connection: default } calls: - [ setAnnotationReader, [ @annotation_reader ] ] 

source: https://github.com/Atlantic18/DoctrineExtensions/issues/1175

0
source