Magento2:从观察者重定向

Magento2: redirect from Observer

我们已经知道如何从观察者重定向 magento 1.x 版本。

但对于 magento 2,我们不知道如何从观察者那里强制进行重定向.

我已经完成了 google,但没有得到任何答案。

是的,我通过研究自己找到了解决方案

如果你想这样做,那么在 your class observer__construct() 函数上你必须注入两个classes.

  • 首先,\Magento\Framework\App\ResponseFactory其中负责 重定向,
  • 另一个 class \Magento\Framework\UrlInterface 这将使 url 对于该重定向。
  • 然后为 ResponseFactory 创建对象,并使用 setRedirect($YourUrl)->sendResponse(); 重定向到您想要的 url.

观察者

<?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();
    }
}

示例:

这里我写了一个重定向的例子。

基本上sales_quote_collect_totals_after事件,我试图强行重定向联系我们。

这里观察者代码:

<?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();
    }
}

重定向到管理控制器

  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();

}
}

这里我正在编写一些用于购物车页面重定向的代码。 在您的模块中创建一个 events.xml 文件

<?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>

在你的观察者文件中 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);

            }
    }

注入 \Magento\Framework\App\ActionFlag $actionFlag$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); 是强制 Magento 停止处理更多事件并从观察者重定向的方式,特别是在使用预调度事件的情况下。

这里是示例代码

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;


}