Magento2.1 Programatically Create Order

Posted on July 20, 2016
Written by

There are plenty of tutorials out there for programatically creating an order in Magento 2.0 however, since upgrading i’ve found that they all no longer work. The error I have been getting is :

Exception #0 (Magento\Framework\Exception\NoSuchEntityException): Cart X does not contain item X

This can be located in :

module-quote/Model/Quote/Item/CartItemPersister.php

It seems that now rather than using :

\Magento\Quote\Model\QuoteFactory
and
\Magento\Quote\Model\QuoteManagement

To save our quote we now need to be using the cart manager

So let me show you the original code I was working with. I followed a tutorial that can be found here by the lovely people over at Webkul

For the sake of this example we can use the object manager to load this class and call orderCreate with some order data like so :

 

So in order to fix the above we need to do a couple of simple changes.

Firstly we need to update the constructor to add the CartRepositoryInterface and CartManagementInterface

after we set the currency we need to save the quote using the cart repository interface In order to actually create our quote object :

This then makes $quote->save() lower down redundant as we don’t want to use the regular quote factory to handle our saving. For the same reasons we don’t want the additional save after collect totals :

Then lastly instead of using the quote management interface to actually create our order from the quote we want to use the cart management interface instead :

And there you go, everything should now be working in Magento2.1

I hope this helps someone out there as I spent a lot of time comparing the original functionality from 2.0 with the admin’s order create process which a rabbit hole of Magento hell!

I’ve put the full class in a gist here

Credit to a lovey person on stack overflow who helped me with the issue. The question can be found here

Thanks for reading !