Magento 2 Redirect From Observer Using Controller Action

Let’s say we have a requirement where we need to redirect the controller to any other action and stop the further dispatch of current action.

To achieve above requirement, you can use the following code snippet:

<?php

namespace Vendor\Modulename\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ActionInterface;

/**
 * Class CustomClass
 * @package Vendor\Modulename\Observer
 */
class CustomClass implements ObserverInterface
{
    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $url;

    /**
     * @var \Magento\Framework\App\ActionFlag
     */
    private $actionFlag;

    /**
     * CustomClass constructor.
     * @param \Magento\Framework\UrlInterface $url
     * @param \Magento\Framework\App\ActionFlag $actionFlag
     */
    public function __construct(
        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\App\ActionFlag $actionFlag
    )
    {
        $this->url = $url;
        $this->actionFlag = $actionFlag;
    }

    /**
     * @param Observer $observer
     * @return $this
     */
    public function execute(Observer $observer)
    {
        $controllerAction = $observer->getControllerAction();
        $redirectionUrl = $this->url->getUrl('ModuleName/ControllerName/ActionName');
        $controllerAction->getResponse()->setRedirect($redirectionUrl);
        $this->actionFlag->set('', ActionInterface::FLAG_NO_DISPATCH, true);
        $this->actionFlag->set('', ActionInterface::FLAG_NO_POST_DISPATCH, true);
        return $this;
    }
}

Hope this helps!

Leave a Reply