0

I'm trying to use the \Magento\Sales\Model\InvoiceOrder class to invoice some orders. If I include the class in my constructor, however, then I get the "Area code not set: Area code must be set before starting a session." error.

I ran a bin/magento setup:di:compile -vvv and found that the exception is being thrown while initialising the "Magento\Payment\Helper\Data" class which requires Magento\Ui\Config\Reader\Definition\Data and goes on to run Magento\Framework\Url->getUrl() which in turn attempts to create a session.

Is there any way to make this work? I can think of three ways to possibly make it work, but I'm not sure if any of them would be considered best-practice:

  1. Use the ObjectManager to get the instance of "InvoiceOrder" rather than Dependency Injection.
  2. Set the Area somewhere, like a class constructor, so it can bypass the issue
  3. Extend one of the base classes (like "\Magento\Framework\Url") with a plugin which either sets the area or catches the exception.

I'm getting around the issue right now using the Object Manager, but it obviously goes against best practices. Would option 3 be considered good practice, or at-least better practice than the other two options? It seems a bit crazy to set the area in a console command even though it won't really be used.

2
  • Can you add your code snippet? Jul 3, 2018 at 14:07
  • Did you ever solve this issue? Looking at exactly the same problem right now and the answer below did not apply as I was already using the mentioned Interface.
    – Louis B.
    Jul 2, 2021 at 8:33

1 Answer 1

0

Please try the following:

In vendor/magento/module-sales/etc/di.xml, you find this line:

<preference for="Magento\Sales\Api\InvoiceOrderInterface" type="Magento\Sales\Model\InvoiceOrder"/>

So, in your constructor, instead of requiring Magento\Sales\Model\InvoiceOrder, better require Magento\Sales\Api\InvoiceOrderInterface.

This will also make your code more robust when upgrading Magento 2, as you now rely on service contracts (as is considered best practise).

Your Answer

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

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