以编程方式切换存储 magento 2



我正在尝试以编程方式切换商店。我使用以下代码来实现它:

/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
public function __construct(
 MagentoStoreModelStoreManagerInterface $storeManager
) {
$this->_storeManager = $storeManager;
}

然后:

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

如 https://magento.stackexchange.com/a/173763/59686

但没有成功。店面上仅显示(选择)默认商店。

我也尝试过这个 url 方案 http://mystoreurl.com/?___store=storeId 但它只显示具有给定 id 的商店,而不是完全切换商店,这意味着当我访问主网址 (http:mystoreurl.com) 时,它再次显示默认存储。有没有办法以编程方式切换商店,就像从管理员那里选择它作为默认值一样。

或者有没有办法添加一些现成的小部件来切换商店(商店切换器)。我使用的主题没有此功能来自动填充商店切换器,因为默认Magento Luma主题提供。

你需要做更多的事情:

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

对于运行清漆 + Amasty GeoIP 重定向的 Magento 2.3,我不得不稍微调整上述内容以使我的工作(在扩展涉及的配置之上)同时进行存储切换:

    /**
     * @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);
    }

最新更新