Amit Bera
Amit Bera

Reputation: 7611

Magento2: redirect from Observer

We have already know that How to redirect from an Observer for magento 1.x version.

but for magento 2,we does not know How to forcefully do redirection from an observer.

I have done google ,but does not get any answer.

Upvotes: 2

Views: 11684

Answers (4)

Zeeshan Khuwaja
Zeeshan Khuwaja

Reputation: 131

injecting the \Magento\Framework\App\ActionFlag $actionFlag and $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);is the way of forcing Magento to stop processing further events and redirect from an observer specially in the case of using predispatch event.

Here is the sample code

public function execute(\Magento\Framework\Event\Observer $observer)
{

    /** @var \Magento\Customer\Controller\Account\LoginPost\Interceptor $controller_action */
    $controller_action = $observer->getData( 'controller_action' );
    $parameters = $controller_action->getRequest()->getParams();
    $session = $this->customerSession;

    if({yourcondition}){


        // setting an action flag to stop processing further hierarchy
        $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);



        /// redirecting back to its referred url
        $observer->getControllerAction()->getResponse()->setRedirect($this->_redirectInterface->getRefererUrl());
        $session->setCustomerFormData($parameters);

    }

    return $this;


}

Upvotes: 3

Jitendra Mohanta
Jitendra Mohanta

Reputation: 270

Here i am writing some code for cart page redirecting. In your module create a events.xml file

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> 
    <event name="controller_action_predispatch_checkout_cart_index">
        <observer name="my_predispatch_checkout_cart" instance="Namespace\Module\Observer\PredispatchCheckoutCart"/>
    </event>
</config>

In your observer file yourmodule\Observer\PredispatchCheckoutCart.php

<?php
    namespace Namespace\Module\Observer;
    use Magento\Framework\Event\ObserverInterface;

    class PredispatchCheckoutCart implements ObserverInterface{
        protected $_objectManager;

        public function __construct(
            \Magento\Framework\ObjectManagerInterface $objectManager,
            \Magento\Checkout\Helper\Cart $_cartHelper
        ) {
            $this->_objectManager = $objectManager;
            $this->_cartHelper = $_cartHelper;
        }

        public function execute(\Magento\Framework\Event\Observer $observer){
                //redirect to cart
                $redirectUrl = $this->_cartHelper->getCartUrl();
                $observer->getControllerAction()->getResponse()->setRedirect($redirectUrl);

            }
    }

Upvotes: 0

Vinoth kumar
Vinoth kumar

Reputation: 475

redirect to admin controller

  namespace sample\test\Observer;
  use \Magento\Framework\Event\Observer;
  use \Magento\Framework\Event\ObserverInterface;


  class SendSecurityCode 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();
        $RedirectUrl= $this->_url->getUrl('welcome/code/index');
        $this->_responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();

}
}

Upvotes: 2

Amit Bera
Amit Bera

Reputation: 7611

Yup, i have find a solution by myself by doing a research

If you want to do that then on __construct() function of your class observer,you must inject two classes.

  • First, \Magento\Framework\App\ResponseFactory which responsible for redirection,
  • Another class \Magento\Framework\UrlInterface which will make url for that redirection.
  • Then create object for ResponseFactory ,and using setRedirect($YourUrl)->sendResponse(); redirect to your wished url.

Observer

<?php
namespace [Vendor]\[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();
             $CustomRedirectionUrl = $this->_url->getUrl('[ModuleName]/[ModuleName]/[[Action]');
            $this->_responseFactory->create()->setRedirect($CustomRedirectionUrl)->sendResponse();
            /* die use for stop excaution */
             die();
    }
}

Example:

Here i am write an example of that redirection.

Basically sales_quote_collect_totals_after event,i was try to forcefully redirect to contact us.

Here the observer code:

<?php
namespace Devamit\Mgoto\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class Challo 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();
        
            $myfile = fopen("var/log/debug.log", "a+") or die("Unable to open file!");
          fwrite($myfile, 'Amitber',true);
          fclose($myfile);
      // $this->_responseFactory->create()->setRedirect('www.google.com')->sendResponse();
           $customerBeforeAuthUrl = $this->_url->getUrl('contact/index/index');
          $this->_responseFactory->create()->setRedirect($customerBeforeAuthUrl)->sendResponse();
       die();
    }
}

Upvotes: 7

Related Questions