Back to Top

Redirect to controller from observer in magento2

Updated 28 March 2024

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.

Searching for an experienced
Magento Company ?
Find out More
<?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);
        }
    }
}

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


5 comments

  • Sn Jha
  • Anu Pahuja
  • ND
    • Pranjali Goel (Moderator)
    • Pranjali Goel (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home