2

I try to use an email template which located in adminhtml area from frontend, the problem is i dont know if changing the state area code is the right way because i alway got an error by doing like this:

      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $area = $objectManager->get('Magento\Framework\App\State');
      $currentAreaCode = $area->getAreaCode();
      $area->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);

1 exception(s): Exception #0 (Magento\Framework\Exception\LocalizedException): Area code is already set

0

That’s because of the following guard clause

#File: vendor/magento/framework/App/State.php
public function setAreaCode($code)
{
    if (isset($this->_areaCode)) {
        throw new MagentoFrameworkExceptionLocalizedException(
            new MagentoFrameworkPhrase('Area code is already set')
        );
    }
    $this->_configScope->setCurrentScope($code);
    $this->_areaCode = $code;
}

The \Magento\Framework\App\State object will only let you set a value once.

Solution: By catching the exception Magento throws and silently ignoring it.

public function __construct(
    \Magento\Framework\App\State $appState,
    $name=null
) {
    try {
        $appState-->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
    } catch (MagentoFrameworkExceptionLocalizedException $e) {
        // intentionally left empty
    }
    parent::__construct($name);
}

Or As per you code

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$area = $objectManager->get('Magento\Framework\App\State');
if (!$area->getAreaCode()) {
    $area->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
}
$currentAreaCode = $area->getAreaCode();
0

You can also try to emulate adminhtml area code by using emulateAreaCode from Magento\Framework\App\State . Check this class implementation as reference: Magento\Widget\Controller\Adminhtml\Widget\Instance\Blocks. I think it's a better solution than just silently ignoring the exception.

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.