Magento2: store manager always returns default store id

Created on 2 May 2016  路  5Comments  路  Source: magento/magento2

I'm implementing module which have to store different data for all stores, so i need get current store id and set id to db with new records. I'm trying get store id this way

$storeId = $this->_storeManager->getStore()->getId();

But when i change scope to another store (which has id "2") then $storeId still has value "1" (default store). I see that last param in my url has changed
store/2/
but in code has returned default store id. Any idea what causing that problem?

All 5 comments

Hi @Rudolfff you should be using MagentoStoreModelStoreResolver::getCurrentStoreId to obtain current store id.

Experienced this on 2.1.2. Fixed in 2.1.3.

Magento CE 2.0.4

Task: get the ID of the current WEBSITE in Admin Panel after saving the settings

events.xml
<event name="admin_system_config_changed_section_current_store">

use Magento\Framework\Event\ObserverInterface;

class CurrentStore implements ObserverInterface
{
    protected $logger;
    protected $store;

    public function __construct(
        \Psr\Log\LoggerInterface $loggerInterface,
        \Magento\Store\Model\StoreResolver $storeResolver 
    )
    {
        $this->logger           = $loggerInterface;
        $this->store            = $storeResolver;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {

        try {
            $_websiteId = $this->store->getCurrentStoreId();
            $this->helper->debug(json_encode($_websiteId));
        } catch (Exception $e) {
            $this->logger->critical($e);
        }
    }
}

I get at all selected websites:
main.DEBUG: "1" {"is_exception":false} []

The same situation:

...
    public function __construct(
        \Psr\Log\LoggerInterface $loggerInterface,
       \Magento\Store\Model\StoreManagerInterface $storeManager
    )
    {
        $this->logger           = $loggerInterface;
        $this->store             = $storeManager;
    }
...
        $_websiteId = $this->store->getWebsite()->getId();
        $this->debug(json_encode($_websiteId));

        $_websiteId = $this->store->getStore()->getWebsiteId();
        $this->debug(json_encode($_websiteId));
...

Return for all selected websites:
main.DEBUG: "1" {"is_exception":false} []

Still added:

use Magento\Store\Model\Website;
use Magento\Store\Model\Store;

-It did not help

Seeing the same problem, please advise.

See https://github.com/magento/magento2/issues/9741 for a solution for this issue.

Was this page helpful?
0 / 5 - 0 ratings