Symfony 2: Disable Doctrine event listener in ContainerAwareCommand
something like this should do the trick :
$searchedListener = null;
$em = $this->getDoctrine()->getManager();
foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
foreach ($listeners as $key => $listener) {
if ($listener instanceof ListenerClassYouLookFor) {
$searchedListener = $listener;
break 2;
}
}
}
if ($searchedListener) {
$evm = $em->getEventManager();
$evm->removeEventListener(array('onFlush'), $searchedListener);
}
else { //listener not found
}
In services.yaml
I have my listener defined this way:
services:
App\EventListener\DoctrinePostUpdateListener:
tags:
- { name: doctrine.event_listener, event: postUpdate }
To my listener class I added private variable $enabled
with condition to stop execution:
class DoctrinePostUpdateListener
{
private $enabled = true;
public function postUpdate(LifecycleEventArgs $args)
{
if ($this->enabled === false) { //stop execution
return;
}
.. your code to execute ..
return;
}
public function setEnabled(bool $enabled)
{
$this->enabled = $enabled;
}
}
and then in my service/controller
code where I don't want to execute this listener I just set this $enable
variable to false:
$listeners = $this->em->getEventManager()->getListeners('postUpdate');
foreach ($listeners as $key => $listener) {
if ($listener instanceof DoctrinePostUpdateListener) {
$listener->setEnabled(false);
break;
}
}