0

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.

Roubi
  • 1,989
  • 1
  • 27
  • 36
  • Yes, see https://stackoverflow.com/questions/22812675/disable-soft-deleteable-filter-for-hard-delete-record-doesnt-work – spackmat Apr 21 '16 at 10:29
  • 1
    @spackmat Your link refers to a different bundle (Gedmo/SoftDeleteable), wihile my answer refers to KnpLabs DoctrineBehaviors SoftDeletable. – Roubi Apr 22 '16 at 01:55
  • Yes, but this also works the same with KnpLabs DoctrineBehaviors SoftDeletable (I implemented it this way in my project). But your own answer is better, so nervermind. ;) – spackmat Apr 23 '16 at 18:48

1 Answers1

2

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

Roubi
  • 1,989
  • 1
  • 27
  • 36
  • This solution doesn't work (anymore?) as described in your linked source. The `knp.doctrine_behaviors.softdeletable_subscriber` service isn't public and can't be accessed without some extra work. So for now it leads to this error: 'You have requested a non-existent service "knp.doctrine_behaviors.softdeletable_subscriber".' – spackmat Apr 28 '16 at 08:22
  • @spackmat You're right. That's what I said to nifr. In my original answer, I only put the link to the github thread, so one could read everything, but it's been edited. I'll change it. – Roubi Apr 28 '16 at 12:56