Magento 2根据客户重定向到不同的商店视图

时间:2019-05-20 13:30:22

标签: magento magento2

我正在使用事件“ controller_action_predispatch”的观察者,以将客户重定向到特定的商店视图(基于某些属性)

问题是据我所知,Magento加载了主题之后,当前的商店视图正在更改。

因此,为了获得所需的结果(每个storeview都具有不同的主题),我必须在成功登录后重新加载页面。

我的events.xml

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

namespace Namespace\Module\Observer;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use \Magento\Store\Model\Store;

class CustomerRedirection implements ObserverInterface
{

    private $_storeManager;
    private $_store_cookie_manager;
    private $_http_context;
    private $_customer_session;
    private $_storeIdsMap;
    private $_storeRepository;
    private $_responseFactory;
    private $_url;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Store\Api\StoreCookieManagerInterface $store_cookie_manager,
        \Magento\Framework\App\Http\Context $http_context,
        \Magento\Customer\Model\Session $customer_session,
        \Magento\Store\Api\StoreRepositoryInterface $storeRepository,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url

    ) {
        $this->_storeManager         = $context->getStoreManager();
        $this->_store_cookie_manager = $store_cookie_manager;
        $this->_http_context         = $http_context;
        $this->_customer_session     = $customer_session;
        $this->_storeRepository      = $storeRepository;
        $this->_responseFactory      = $responseFactory;
        $this->_url                  = $url;

        $this->_storeIdsMap = //Store ids map

    }

    private function changeStoreView($storeId)
    {
        $stores = $this->_storeManager->getStores();

        foreach ($stores as $store) {
            if ($storeId === $store['store_id']) {

                $this->_storeManager->setCurrentStore($storeId);
                $store = $this->_storeRepository->getActiveStoreByCode($store->getCode());
                $this->_http_context->setValue(Store::ENTITY, $store->getCode(), $store->getCode());
                $this->_store_cookie_manager->setStoreCookie($store);

                return;
            }
        }
    }

    public function execute(EventObserver $observer)
    {

        $this->changeStoreView(//Store View Id Here);
        return $this;
    }
}

试图返回一个新的响应对象(包含新的重定向路径),并在LoginPost控制器中使用一个插件,但未成功

0 个答案:

没有答案