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 🙂
Categories:
Magento2
Tags:
Add A Product In Existing Order Magento 2 add new product in order magento 2 magento 2 add item in existing order
View Comments
Comment or Ask a Question
Quick Links