Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
ARTICLE

Add A Product In Existing Order Magento 2

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 🙂

. . .

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