0

How to redirect from Observer in Magento2 ? I am using the below code:

$controller = $observer->getControllerAction();
$action = $this->_request->getActionName();
$this->_actionFlag->set($action, \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
$controller->getResponse()->setRedirect('sales/order/address', array('address_id' => $addressId));
return $this;

event.xml

<event name="controller_action_predispatch_sales_order_addressSave">
    <observer name="verify_cod" instance="XXX\Ccc\Observer\Pincode" />
</event>
0

2 Answers 2

0

Try the following code to do redirects on observer:

 $url = $this->urlInterface->getUrl('customer/account/login');
            $observer->getControllerAction()
                ->getResponse()
                ->setRedirect($url);
6
0

You have to use constructor for it.

Below code working for me.

namespace ......

class something
{
public function __construct(

    \Magento\Framework\App\ResponseFactory $responseFactory,
    \Magento\Framework\UrlInterface $url,

) {
    $this->_responseFactory = $responseFactory;
    $this->_url = $url;

}

 public function execute()
{
   $CustomRedirectionUrl = $this->_url->getUrl('*/*/');
    $this->_responseFactory->create()->setRedirect($CustomRedirectionUrl)->sendResponse();
    exit();
}
}
2
  • No,Its not observer.php but constructor for redirection is same for all.
    – anonymous
    Commented Feb 16, 2018 at 13:28
  • why.. use exit() in this place
    – Mahi M
    Commented Feb 16, 2018 at 13:37

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