Console Command: Area code must be set before starting a session
-
30-09-2020 - |
Question
I am trying to get a list of orders from the OrderRepository (Magento 2.1) via a console command and am using code as follows...
...
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
$data = []
) {
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
public function execute()
{
$sc = $this->searchCriteriaBuilder->create();
$items = $this->orderRepository->getList($sc);
}
...
This code throws an error of:
[Magento\Framework\Exception\SessionException]
Area code not set: Area code must be set before starting a session.
[Magento\Framework\Exception\LocalizedException]
Area code is not set
I have attempted to resolve it by passing in the appState (\Magento\Framework\App\State $appState
) and calling setAreaCode with either frontend
, crontab
, admin
and adminhtml
- none of which seem to have any effect.
I have managed to resolve it by adding an echo at the top of the execute function..
public function execute()
{
echo 'Please please dont throw an exception';
$sc = $this->searchCriteriaBuilder->create();
$items = $this->orderRepository->getList($sc);
}
Am I missing something glaringly obvious? Or is this a bug in Magento?
Solution
Figured it out; it's because in my console script I was calling another class - and because it was to test some code I had been lazy and was calling my class via:
$model = $this->objectManager->create('{ns}\{module}\Model\{class}');
$model->execute();
It seems doing this throws the area code error up.. with it properly injected and calling $this->processor->execute();
instead of referencing the Object Mananger directly. Guess this is another negative for using the OM.
In this case I was just implementing a CLI command to test some code; hence the reason for being a little lazy.