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 🙂
Be the first to comment.