Back to Top

How To Modify Existing Order Magento 2

Updated 6 January 2023

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 = '122';
$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());
$items =  $quote->getAllItems();

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 🙂

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Arpita
    • Subhangi (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home