Magento 2 offers a robust system for order management, but sometimes, you may need to change the order status programmatically rather than manually.
Whether it’s updating order details, changing the status, or modifying item quantities, knowing how to edit an order programmatically can save time and ensure accuracy.
This blog will guide you through the steps to edit order in Magento 2 programmatically.
Follow the Steps to Edit Order in Magento 2 Programmatically
// app/code/YourVendor/YourModule/registration.php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'YourVendor_YourModule', __DIR__ ); |
<!-- app/code/YourVendor/YourModule/etc/module.xml --> <?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="YourVendor_YourModule" setup_version="1.0.0"> </module> </config> |
Load Order and Quote:
<?php $orderId =121; $order = $objectManager->create('Magento\Sales\Model\Order')->load($orderId); $quote = $objectManager->create('\Magento\Quote\Model\Quote')->load($order->getQuoteId()); |
Get Items from Quote:
$items = $quote->getAllItems(); |
Update Quote Items:
foreach ($items as $quoteItem) { $origOrderItem = $order->getItemByQuoteItemId($quoteItem->getId()); // Update quote item according to your needs //example for change product $quoteItem->setProductId(3); $quoteItem->save(); $origOrderItem->setProductId(3); $quoteItem->save(); //example for change Qty $quoteItem->setQty(3); $quoteItem->save(); $origOrderItem->setQtyOrdered(3); $quoteItem->save(); } $quote->collectTotals(); $quote->save(); |
Update Order Items:
foreach ($items as $quoteItem) { $orderItem = $quoteToOrder->convert($quoteItem); $origOrderItemNew = $order->getItemByQuoteItemId($quoteItem->getId()); if ($origOrderItemNew) { $origOrderItemNew->addData($orderItem->getData()); } else { if ($quoteItem->getParentItem()) { $orderItem->setParentItem( $order->getItemByQuoteItemId($orderItem->getParentItem()->getId()) ); } $order->addItem($orderItem); } } // Set order totals $order->setSubtotal($quote->getSubtotal()) ->setBaseSubtotal($quote->getBaseSubtotal()) ->setGrandTotal($quote->getGrandTotal()) ->setBaseGrandTotal($quote->getBaseGrandTotal()); // Save changes $quote->save(); $order->save(); |
Conclusion
Thank you for coming to the end of our blog. Via this article, I hope that Magento stores can now find a solution for updating their created orders.
MageAnts Magento 2 edit order promised to bring great improvement in updating orders with pop-up, no order cancellation required with extra edit fields.
Managing and updating orders has become easier and more convenient than ever!