3

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

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

protected $_storeManager;

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

接着:

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

https://magento.stackexchange.com/a/173763/59686中给出的

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

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

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

4

2 回答 2

3

你需要做更多:

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

}
于 2018-05-10T08:56:15.480 回答
0

对于运行 Varnish + Amasty GeoIP Redirect 的 Magento 2.3,我必须稍微调整上面的内容以使我的工作(在与扩展有关的配置之上)同时存储切换:

    /**
     * @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);
    }
于 2021-03-05T04:41:49.357 回答