Redirect to controller from observer in magento2
Here I am going to explain, how you redirect to a controller/action from the observer.
Step 1. We need to create an events.xml file inside the etc/frontend/ then write the below code inside this file.
<event name="controller_action_predispatch_review"> <observer name="catalog_review_enabled" instance="Company\Module\Observer\CustomObserver" /> </event>
Step 2. Create an observer file under app/code/Company/Observer/CustomObserver.php
In the following observer, I am redirecting review routes to 404 when the review module is disabled.
<?php namespace Company\Module\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Message\ManagerInterface; use Magento\Store\Model\ScopeInterface; class CustomObserver implements ObserverInterface { /** * Configuration path to review active setting */ const XML_PATH_REVIEW_ACTIVE = 'catalog/review/active'; /** * @var \Magento\Framework\ObjectManagerInterface */ protected $_objectManager; /** * @var \Magento\Framework\UrlInterface */ protected $_urlInterface; /** * [__construct ] * * @param \Magento\Framework\ObjectManagerInterface $objectManager * @param \Magento\Framework\UrlInterface $urlInterface */ public function __construct( \Magento\Framework\ObjectManagerInterface $objectManager, ScopeConfigInterface $scopeConfig, \Magento\Framework\UrlInterface $urlInterface ) { $this->_objectManager = $objectManager; $this->scopeConfig = $scopeConfig; $this->_urlInterface = $urlInterface; } public function execute(\Magento\Framework\Event\Observer $observer) { if (!$this->scopeConfig->getValue( self::XML_PATH_REVIEW_ACTIVE, ScopeInterface::SCOPE_STORE ) ) { $defaultNoRouteUrl = $this->scopeConfig->getValue( 'web/default/no_route', ScopeInterface::SCOPE_STORE ); $redirectUrl = $this->_urlInterface->getUrl($defaultNoRouteUrl); $observer->getControllerAction() ->getResponse() ->setRedirect($redirectUrl); } } }
5 comments