10

I want to check whether it is front or backend.
How can I do that?

19

Read More: blog.mageprince.com

With objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode(); //frontend or adminhtml or webapi_rest

With Dependency Injection

protected $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function getArea()
{
    return $this->_state->getAreaCode();
}

Note: As per magento2 coding standards don't use object manager instance directly in files

  • 1
    +1 for the Dependency injection – PЯINCƏ Sep 6 '18 at 9:22
  • +1 @PЯINCƏ As per Magento coding standard, Don't use full class name in construct method. Declare full class using the use statement and declare only class name to construct() method. – Rakesh Jesadiya Aug 22 at 12:48
  • 1
    @RakeshJesadiya Im not agree with you, please see this question : magento.stackexchange.com/questions/106096/… – PЯINCƏ Aug 22 at 12:55
5

People have answered the question already. I am just making it better.

const AREA_CODE = \Magento\Framework\App\Area::AREA_ADMINHTML;

private $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function isAdmin()
{
    $areaCode = $this->_state->getAreaCode();

    if ($areaCode == self::AREA_CODE) {
        return true;
    } else {
        return false;
    }
}
3

Use below code

$objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectmanager->get('Magento\Framework\App\State');
if($state->getAreaCode() == 'frontend')
  //frontend
else
  //backend
2

Try code below for check if you are in admin area

function df_is_admin($store = null) {
    /** @var \Magento\Framework\ObjectManagerInterface $om */
    $om = \Magento\Framework\App\ObjectManager::getInstance();
    /** @var \Magento\Framework\App\State $state */
    $state =  $om->get('Magento\Framework\App\State');
    return 'adminhtml' === $state->getAreaCode();
}
0
 public function isAdmin(){
      return ('adminhtml' == $this->_state->getAreaCode());
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.