How to disable an event observer in Magento 2
As a Magento 2 developer sometimes you might need to completely disable a specific event that is implemented either in native code or a 3rd party module. One option would be to override the observer method however that is not a good practice. Instead there is a better way. You should use the native disabled attribute. Here is an example on how to disable the controller_action_noroute event. Originally define in CMS native module:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_noroute">
<observer name="cms" instance="Magento\Cms\Observer\NoRouteObserver" />
</event>
<event name="controller_action_nocookies">
<observer name="cms" instance="Magento\Cms\Observer\NoCookiesObserver" />
</event>
</config>
In order to disable the event we need to create a new xml file and define the same event with disabled property set to true.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_noroute">
<observer name="cms" disabled="true" />
</event>
</config>
This works because the dispatch method in Invoker class checks for the node and if the value is true the observer method is not called. Take a look at the method to understand this:
public function dispatch(array $configuration, Observer $observer)
{
/** Check whether event observer is disabled */
if (isset($configuration['disabled']) && true === $configuration['disabled']) {
return;
}
...
$this->_callObserverMethod($object, $observer);
}
That is it for this article. Hopefully this comes in handy when developing Magento 2.