Reading list Switch to dark mode

    Add A Product In Existing Order Magento 2

    Updated 6 January 2023

    Add A Product In Existing Order Magento 2 : In this post we will learn how to add new product in existing order.
    so first of all we need to add the product in quote then in order.
    please check below code.

    <?php
    $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $order = $this->_objectManager
            ->create(
                'Magento\Sales\Model\Order'
            )->load($orderId);
    $quote = $this->_objectManager
            ->create(
                '\Magento\Quote\Model\Quote'
            )->load($order->getQuoteId());
    $product = $this->_objectManager
            ->create(
                'Magento\Catalog\Model\Product'
            )->load($productId);
            
    $this->_objectManager->create(
                'Magento\Quote\Model\Quote\Item'
            )->setProduct($product)
            ->setQuote($quote)
            ->setQty($productQty)
            ->save();
            $quoteToOrder = $this->_objectManager
            ->create(
                'Magento\Quote\Model\Quote\Item\ToOrderItem'
            );
    $quote->collectTotals();
    $quote->save();
    $items = $quote->getAllItems();
    foreach ($items as $quoteItem) {
        $orderItem = $quoteToOrder->convert($quoteItem);
        $origOrderItemNew = $order->getItemByQuoteItemId($quoteItem->getId());
    
        if (!$orderItem) {
            $origOrderItemNew->addData($orderItem->getData());
            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());
    $order->save();
    

    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*


    Be the first to comment.

    Back to Top

    Message Sent!

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

    Back to Home