繁体   English   中英

Magento2:从观察者重定向

[英]Magento2: redirect from Observer

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

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

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

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

如果要执行此操作,则必须 your class observer __construct()函数上注入两个类

  • 首先, 负责重定向的 \\Magento\\Framework\\App\\ResponseFactory
  • 另一个类\\Magento\\Framework\\UrlInterface ,它将为该重定向创建url。
  • 然后为ResponseFactory创建对象,并使用setRedirect($YourUrl)->sendResponse(); 重定向到您希望的网址。

观察者

<?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\\Magento\\Framework\\App\\ActionFlag $actionFlag $this->_actionFlag->set('', \\Magento\\Framework\\App\\Action\\Action::FLAG_NO_DISPATCH, true); 这是强制Magento停止处理其他事件并从观察者重定向的方法,特别是在使用predispatch事件的情况下。

这是示例代码

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;


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM