一般的想法是通过请求参数传递选择的范围。
我认为您应该在产品编辑操作中使用类似的代码:
/** @var \Magento\Store\Model\StoreManagerInterface $storeManager */
$storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$storeId = (int) $this->getRequest()->getParam('store', 0);
$store = $storeManager->getStore($storeId);
$storeManager->setCurrentStore($store->getCode());
在这种情况下,$store->getWebsiteId()
应该是实际的(选定的)网站ID。但这只能在您使用存储块的情况下进行,该存储块的工作方式与标准magento块相同(选择存储范围):
这是我选择默认商店视图(id == 1)时的示例结果:
这是默认的全局范围(“ 所有商店视图 ”的网站ID为0):
更新:
您可以在助手中添加这样的方法,并在需要的地方使用它:
/**
* @var \Magento\Framework\App\State
*/
protected $state;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* Data constructor.
* @param Context $context
* @param \Magento\Framework\App\State $state
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
*/
public function __construct(
Context $context,
\Magento\Framework\App\State $state,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
parent::__construct($context);
$this->state = $state;
$this->storeManager = $storeManager;
}
/**
* @return int
*/
public function resolveCurrentWebsiteId()
{
if ($this->state->getAreaCode() == \Magento\Framework\App\Area::AREA_ADMINHTML) {
// in admin area
/** @var \Magento\Framework\App\RequestInterface $request */
$request = $this->_request;
$storeId = (int) $request->getParam('store', 0);
} else {
// frontend area
$storeId = true; // get current store from the store resolver
}
$store = $this->storeManager->getStore($storeId);
$websiteId = $store->getWebsiteId();
return $websiteId;
}
结果应该是这样的:
没有范围选择器的后端-0
具有范围选择器支持- 选定的网站ID;如果未选择则为0(所有商店视图)
前端- 当前网站ID
如果您正在寻找前端的短途路线:
您可以Magento\Store\Model\StoreResolver
为此目的使用该类:
/**
* @var \Magento\Store\Model\StoreResolver
*/
private $storeResolver;
/**
* @param \Magento\Store\Model\StoreResolver $storeResolver
*/
public function __construct(
\Magento\Store\Model\StoreResolver $storeResolver
) {
$this->storeResolver = $storeResolver;
}
/**
* Returns the current store id, if it can be detected or default store id
*
* @return int|string
*/
public function getCurrentStoreId()
{
return $this->storeResolver->getCurrentStoreId();
}
它可以正确检测前端区域上当前选择的商店视图,但对于管理区域没有用。