Categories


Archives


Recent Posts


Categories


Magento 2: Store Object Loses `isAdmin` Method in Dev 54

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

The Magento 2 team just threw dev-54 over the wall. One change you’ll notice quickly is they’ve removed the isAdmin method from the store object. This is the method that, in theory, allows a Magento client programmer to know if Magento is or is not running in the backend admin console.

I say in theory, because “running in the backend admin console” is not a clearly defined thing in Magento 1. The isAdmin method checks the ID value for the store object. If it’s 0, Magento 1 thinks it’s “running in the backend admin console”. Unfortunately, there are times where this isn’t 100% accurate. Magento 1 runs with an admin store ID during API requests (unless changed by the user), and many command line scripts run with a store ID of zero as well. There was even a bug in earlier versions of Magento where the Magento Connect packager section would return false for an isAdmin check. This remained unfixed/unnoticed for years.

Fortunately, Magento 2’s blessing-and-fleshing-out-of the (in Magento 1) loosely defined “area” concept means we can be more precise about what we’re checking for as Magento client programmers.

Right now you can recreate the behavior of isAdmin with the following code.

$om         = MagentoAppObjectManager::getInstance(); 
$app_state  = $om->get('MagentoAppState');
$area_code  = $app_state->getAreaCode();
if($app_state->getAreaCode() == MagentoBackendAppAreaFrontNameResolver::AREA_CODE)
{
    echo "is the admin";
}
else
{
    echo "is NOT the admin";
}

This uses the MagentoAppState object to grab the area code, and if it’s equal to adminhtml (the value stored in the MagentoBackendAppAreaFrontNameResolver::AREA_CODE constant), you know Magento is running in the adminhtml area. This sort of thing isn’t possible in Magento 1. While there are many things you can check, knowing for certain what area your code runs in is, at best, a fuzzy prospect.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 29th November 2013

email hidden; JavaScript is required