3

I'm trying to determine on a plugin if the request comes from admin or for frontend. I had to make a plugin for Magento\Framework\App\Config\ScopeConfigInterface, and in my plugin I need to detect the area code on my aroundGetValue function. I'm trying this:

$om = \Magento\Framework\App\ObjectManager::getInstance();
$area = $om->get('Magento\Framework\App\State');
$areaCode= $area->getAreaCode();

But when I deploy my code I'm getting this error:

[Magento\Framework\Exception\LocalizedException]
  Area code is not set

I don't know how to check at that level if the request comes from admin or for frontend. Can anyone help me with this?

2 Answers 2

1

On your construct, put:

public function __construct(\Magento\Framework\App\State $state)
{
   $state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);
}

And try again

4
  • Hi Max! If I set the area code, then on the function where I need to get the area code I will get the area code that I setted on the construct, that won't be the real one Jan 23, 2018 at 21:51
  • Ah ok, if you change setAreaCode for getAreaCode or you can check current url
    – Max Souza
    Jan 23, 2018 at 22:01
  • not advisable to set area code in construct as it can break a lot of things, do it somewhere else in the class with a try catch if you need to check if its set first
    – DWils
    Jun 21, 2019 at 21:45
  • That doesn't answer the question. May 15 at 14:36
0

I'd suggest to put your events.xml file not in etc/, but in etc/adminhtml/ and in etc/frontend/ with different methods. That way you can be sure that your observer is only called in the correct areas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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