How to get current Website ID in the Admin Panel?
The general idea is to pass the scope, chosen, through the request parameter.
I think you should use the similar code like in the product edit action:
/** @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());
In this case $store->getWebsiteId()
should be actual (selected) website id. But this can be done only in case you use the store block which works in the same way as a standard magento block (to select a store scope):
Here is my result in the example when I select the default store view (id == 1):
and here is for the default global scope (All Store Views, website id is 0):
Update:
You can add a method like this in the helper and use it where you want:
/**
* @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;
}
Result should be like this:
Backend without scope selector - 0
Backed with scope selector - selected website id or 0 if nothing selected (All Store Views)
Frontend - current website id
If you are looking for the short-way on the frontend:
You can use the Magento\Store\Model\StoreResolver
class for that purpose:
/**
* @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();
}
It is correctly detects the currently selected store view on the frontend area, but useless for the admin area.