I working with a custom extension related with multiple websites. I face with an issue, define a script code execute in the Admin Panel by getting Website Id. I expected result website_id
like 0 (default ID in store_website
table). But when I using this function below it always return 1.
/** @var \Magento\Store\Model\StoreManagerInterface */
$this->_storeManager->getStore()->getWebsiteId(); //return 1, expect 0
$this->_storeManager->getWebsite()->getId(); //return 1
My Question: Any way to get current
website_id
in the Admin Panel or define a function run inadminhtml
area?Note: This function needs to work on both the frontend and backend.
Any help would be appreciated.
Best Answer
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:
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:
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:It is correctly detects the currently selected store view on the frontend area, but useless for the admin area.