cancel
Showing results for 
Search instead for 
Did you mean: 

How change store view using code when starting session - Magento 2

How change store view using code when starting session - Magento 2

Hi!

 

I want to make a change of store view through code. I have created the next plugin for when the user logs in the system makes a change of store view, but the change is not maintained, I want to switch to store view DE but when I open a product or a category the change is lost. This is my code:

 

<?php
namespace MyPlugin\CustomerLogin\Plugin;

class LoginPostPlugin
{

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManagerInterface;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
    ) {
        $this->_storeManagerInterface = $storeManagerInterface;
    }


    public function afterExecute(
        \Magento\Customer\Controller\Account\LoginPost $subject,
        $result)
    {
        //-- check group is retail customer or not
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        if ($customerSession->isLoggedIn()){
            $groupId = $customerSession->getCustomerGroupId();
            if ($groupId == 2){
                $this->_storeManagerInterface->setCurrentStore(2);
                $result->setPath('?___store=DE&___from_store=EN');
            }
        }
        return $result;
    }
}

 

Can someone help me solve my problem? I need to simulate the change of store view but I need the change to be maintained

2 REPLIES 2

Re: How change store view using code when starting session - Magento 2

Hello @ManuelSissl 

 

$result->setPath('?___store=DE&___from_store=DE');

from_store means what is your current store.


Problem solved? Click Kudos & Accept as Solution!
Sunil Patel
Magento 2 Certified Professional Developer & Frontend Developer

Re: How change store view using code when starting session - Magento 2

Hi,

 

Yes but it does not work! The change of store view works, but if I open a category or a product, the store returns to the shop window where it was before (EN). Do you have any suggestions to solve my problem?