Search code examples
symfonydoctrine-ormdoctrinesoft-delete

Symfony2, KnpLabs DoctrineBehaviors: How do I truly delete a softdeletable entity?


Is there a way to override the softdeletable behaviour with KNPLabs DoctrineBehaviors from a controller?

In my action, I would like to be able to momentarily "disable" the softdeletable behaviour so I can truly remove my entity from the database instead of just setting the deletedAt field.


Solution

  • nifr kindly gave me an answer on Github: https://github.com/KnpLabs/DoctrineBehaviors/issues/294#issuecomment-190310921:

    Quick 'n dirty:

    $entityManager = $this->getDoctrine()->getManager('default');
    $eventManager = $entityManager->getEventManager();
    
    // remove the softdeletable subscriber
    $subscriber = $this->get('knp.doctrine_behaviors.softdeletable_subscriber');
    $eventManager->removeEventListener($subscriber->getSubscribedEvents(), $subscriber);
    
    // remove entity while the subscriber is removed
    $entityManager->remove($entity);
    $entityManager->flush();
    
    // add back the subscriber
    $eventManager->addEventSubscriber($subscriber);
    

    PROBLEM This triggers the error "you have requested a non-existent service", because the service is not public.

    To resolve this issue, according to nifr, 2 possible solutions:

    1) define your controller itself as a service and inject the subscriber-service explicitly
    2) create a factory-service that would return the subscriber service and call that one in your controller