Magento 2 Redirect From Observer We can use setRedirect($redirectUrl)->sendResponse(); to redirect to specified page from observer. Here in this article we are going to explain this with simple example.
Magento 2 Redirect From Observer Example
You can redirect from observer simply as below-
Observer-
Here is a simple observer which redirects to specified url in Magento2.
Magento 2 Redirect From Observer Example:
<?php namespace VendorName\ModuleName\Observer; use \Magento\Framework\Event\Observer; use \Magento\Framework\Event\ObserverInterface; class YourClass implements ObserverInterface { protected $_responseFactory; protected $_url; public function __construct( \Magento\Framework\App\ResponseFactory $responseFactory, \Magento\Framework\UrlInterface $url ) { $this-?>_responseFactory = $responseFactory; $this->_url = $url; } public function execute(Observer $observer) { $event = $observer->getEvent(); $customUrl = 'customer/login';// your custom url $this->_responseFactory->create()->setRedirect($customUrl)->sendResponse(); exit(); } } ?> |