Question

I get "Area code not set error" when my observer executes. What can I do?

Code:

<?php

namespace MyCompany\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\App\Bootstrap;

class SaveOrder implements ObserverInterface
{
    private $logger;
    private $state;

    public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\App\State $state
    ) {
        $this->_layout = $context->getLayout();
        $this->_request = $context->getRequest();
        $this->logger = $logger;
        $this->_state = $state;

        try {
            $this->_state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            // nothing to do
        }

    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {

        $bootstrap = Bootstrap::create(BP, $_SERVER);
        $objectManager = $bootstrap->getObjectManager();
        $objDate = $objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
        $date = $objDate->gmtDate();

        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $orderId = $observer->getEvent()->getOrderIds()[0];

        $sql = "INSERT INTO sap_orders (entity_id, order_id, sent, timestamp) Values (''," .
            $orderId .
            ", '" .
            "0" .
            "', '" .
            $date .
            "')" ;
        $connection->query($sql);

    }
}
Was it helpful?

Solution

You need to set Area code(Frontend/Backend) when using bootstrap class

public function execute(\Magento\Framework\Event\Observer $observer)
{

    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
     $state = $objectManager->get('Magento\Framework\App\State');
     $state->setAreaCode('frontend');
    (or)
     $state = $objectManager->get('Magento\Framework\App\State');
     $state->setAreaCode('backend');
    $objDate = $objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
    $date = $objDate->gmtDate();

    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();
    $orderId = $observer->getEvent()->getOrderIds()[0];

    $sql = "INSERT INTO sap_orders (entity_id, order_id, sent, timestamp) Values (''," .
        $orderId .
        ", '" .
        "0" .
        "', '" .
        $date .
        "')" ;
    $connection->query($sql);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top