skip to Main Content

I am trying to switch stores programmatically. I used following code to achieve it:

/**
* @var MagentoStoreModelStoreManagerInterface
*/

protected $_storeManager;

public function __construct(
 MagentoStoreModelStoreManagerInterface $storeManager
) {
$this->_storeManager = $storeManager;
}

and then:

$this->_storeManager->setCurrentStore('YOUR_STORE_ID');

as given in https://magento.stackexchange.com/a/173763/59686

But no success. Only default store is displayed(selected) on storefront.

I have also tried this url scheme http://mystoreurl.com/?___store=storeId but it only display the store with given id instead of switching the store completely, Means when i visit the main url (http:mystoreurl.com), it is again displaying default store. Is there any way to switch the store programmatically just like it is selected as default from admin.

Or is there any way to add some readymade widget to switch stores (Store Switcher). The theme I am using does not have this feature to auto populate store switcher as default Magento Luma theme provides.

2

Answers


  1. you need to do more:

    use MagentoStoreModelStore;
    use MagentoFrameworkAppHttpContext as HttpContext;
    use MagentoStoreApiStoreCookieManagerInterface;
    use MagentoStoreApiStoreRepositoryInterface;
    
    [...]
    
    public function __construct
    (
        HttpContext $httpContext,
        StoreCookieManagerInterface $storeCookieManager,
        StoreRepositoryInterface $storeRepository
    
    ) {
        $this->httpContext = $httpContext;
        $this->storeCookieManager = $storeCookieManager;
        $this->storeRepository = $storeRepository;
    }
    
    [...]
    
    public function yourFunction(){
    
        $store = $this->storeRepository->getActiveStoreByCode('YOUR_STORE_CODE');
        $this->httpContext->setValue(Store::ENTITY, 'YOUR_STORE_CODE', 'DEFAULT_STORE_CODE');
        $this->storeCookieManager->setStoreCookie($store);
    
    }
    
    Login or Signup to reply.
  2. For Magento 2.3 running Varnish + Amasty GeoIP Redirect I had to slightly adjust the above to get mine working (on top of the configuration involved with the extension) whilst store switching:

        /**
         * @param string $storeCode
         * @param MagentoStoreModelStore $store
         * @return void
         */
        private function switchStore(string $storeCode, MagentoStoreModelStore $store): void
        {
            /** @var MagentoFrameworkAppHttpContext */
            $this->httpContext->setValue(MagentoStoreModelStore::ENTITY, $storeCode, $storeCode);
            
            /** @var MagentoStoreApiStoreCookieManagerInterface */
            $this->storeCookieManager->setStoreCookie($store);
    
            /** @var MagentoStoreModelStoreManagerInterface */
            $this->storeManager->setCurrentStore($store);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search