1

I have a custom observer and I am intercepting calls in some situation I want to return some specific data and prevent Magento to proceed with its flow, how can I achieve this without using die or exit in Magento 2?

my event.xml is like :

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="controller_action_predispatch">
      <observer name="my_observer" instance="MyObserver" shared="false" />
  </event>
</config>

and my cobserver looks like

class MyObserver implements ObserverInterface
{
  public function __construct(
  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  \Magento\Framework\App\State $state)
  {

  }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    $action = $observer->getEvent()->getControllerAction();
    //if(X exist in cookie)
            {
                $response = $action->getResponse();
        $response->setRedirect($result->redirectUrl)->sendResponse();
                return;
            }
    else if(Y exist in cookie)
       {

                $response->setHeader('YResult', 'Y Result');
        //Send for example empty body from here to client and prevent Magento 2 to continue
       }
    else
        {
        //Do nothing continue normal flow
        }

  }
}

in the first if I was able to send redirect header and stop the normal flow by

$response->setRedirect($result->redirectUrl)->sendResponse();

but for the second if I do not want response with redirect, I want to send empty a response with a custom header (custom javascript on client side will pick up the answer and react to it )

  • 1
    can you please add your code and give more detail about event and condition. – Abhishek Panchal Feb 13 '18 at 19:20
  • 1
    try throwing an exeption :) it worked for me on M1.9.x worth a shot on the M2 too. – Macas Feb 13 '18 at 19:22
1

Observers are not supposed to use for stop flow. Use plugins instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.