Redirect to controller from observer in magento2

Redirect to controller from observer in magento2

Here I am going to explain, how you redirect to a controller/action from any observer.

Create an observer file under app/code/Company/Observer/CustomObserver.php

In the following observer I am redirecting to the (“checkout/cart/index”) cart controller .

<?php
namespace Company\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\ManagerInterface;

class CustomObserver implements ObserverInterface
{
    /**
     * @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,
        \Magento\Framework\UrlInterface $urlInterface
    ) {
        $this->_objectManager = $objectManager;
        $this->_urlInterface = $urlInterface;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        
        $url = $this->_urlInterface->getUrl('checkout/cart/index'); // give here your controller/action
        // below code redirects to cart controller
        $observer->getControllerAction()
                    ->getResponse()
                    ->setRedirect($url);
    }
}

 

. . .

Comments (5)

Add Your Comment

  • Sn Jha
    yes it is not working. do we have another option?
  • Anu Pahuja
    its not working with ‘checkout_submit_before’. Error ‘getResponse on null’
  • ND
    How to set Message and display it on cart page?
    • Pranjali Goel
      you can add error/notice/success through object of Magento\Framework\Message\ManagerInterface before redirecting to cart page.
    • Pranjali Goel
      you can add error/notice/success message through object of Magento\Framework\Message\ManagerInterface before redirecting to cart page.
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close