Switch store programmatically magento 2

Viewed 6670

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

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/

protected $_storeManager;

public function __construct(
 \Magento\Store\Model\StoreManagerInterface $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

you need to do more:

use Magento\Store\Model\Store;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Store\Api\StoreCookieManagerInterface;
use Magento\Store\Api\StoreRepositoryInterface;

[...]

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

}

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 Magento\Store\Model\Store $store
     * @return void
     */
    private function switchStore(string $storeCode, \Magento\Store\Model\Store $store): void
    {
        /** @var Magento\Framework\App\Http\Context */
        $this->httpContext->setValue(\Magento\Store\Model\Store::ENTITY, $storeCode, $storeCode);
        
        /** @var Magento\Store\Api\StoreCookieManagerInterface */
        $this->storeCookieManager->setStoreCookie($store);

        /** @var Magento\Store\Model\StoreManagerInterface */
        $this->storeManager->setCurrentStore($store);
    }
Related