Skip to content

Admin always return default store code, not admin #3147

@hiephm

Description

@hiephm

In admin controller, the following code will not work as expected (always return false):

/** @var \Magento\Store\Model\StoreManagerInterface $storeManager */
$storeManager->getStore()->getCode() == \Magento\Store\Model\Store::ADMIN_CODE;

because the 'admin' store code is not set anywhere in Action class.
Magento 1 does this properly by hooking to 'adminhtml_controller_action_predispatch_start' event and set it:

// in Mage_Adminhtml_Model_Observer
    public function bindStore()
    {
        Mage::app()->setCurrentStore('admin');
        return $this;
    }

Following code doesn't work, see update below:
Magento 2 does not have such event, but we can use 'controller_action_predispatch' in adminhtml/events.xml in any module, then set 'admin' store code:

/** @var \Magento\Store\Model\StoreManagerInterface $storeManager */
$this->storeManager->setCurrentStore('admin');

I can create a pull request if necessary.

UPDATE 1: above fix will cause unset of website when saving products, there maybe easier ways to check if current store is admin, now I am using \Magento\Backend\Model\Auth::isLoggedIn()

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions