How To Modify Existing Order Magento 2

How To Modify Existing Order Magento 2 => Today we will learn how to modify existing order at magento. sometime we need to modify existing order. that has been placed by the customer, like we need to increase or decrease the quantity , change the price etc.
so i will explain below how to do that.

$orderId = '21';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$quoteToOrder = $objectManager
            ->create(
                'Magento\Quote\Model\Quote\Item\ToOrderItem'
            );

$order = $objectManager
           ->create(
                     'Magento\Sales\Model\Order'
           )->load($orderId);

$quote = $objectManager
        ->create(
            '\Magento\Quote\Model\Quote'
        )->load($order->getQuoteId());


first we need to update the order quote.

foreach ($items as $quoteItem) {
    $origOrderItem = $order->getItemByQuoteItemId($quoteItem->getId());
    $orderItemId = $origOrderItem->getItemId();
    //update quote item according your need 
}
$quote->collectTotals();
$quote->save();

now we have to update the order

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);
    }
}
$order->setSubtotal($quote->getSubtotal())
    ->setBaseSubtotal($quote->getBaseSubtotal())
    ->setGrandTotal($quote->getGrandTotal())
    ->setBaseGrandTotal($quote->getBaseGrandTotal());
$quote->save();
$order->save();

this is the process to modify the existing order.
hope so it will help 🙂

. . .

Ask a Feature