1

How can I add an item to an order programmatically? I know the sku and product id of the product that I want to add, as well as the quantity. I also know the order which I want to add it to, and I can get a \Magento\Sales\Api\Data\OrderInterface object, on which I can call setItems to add the item, but I don't know how to create the new \Magento\Sales\Api\Data\OrderItemInterface from only the sku, product id and quantity, since I want other attributes such as the base price, etc. to be populated automatically.

  • Where are you calling this code from ? do you have access to the cart object ? – William Tran Jan 31 '18 at 5:35
1

A bit more context would help but generally, you don't add item to Order. You add item to the quote, then submit the quote (place order).

I won't go into too much detail because I don't know where you are calling this code from, but you will have to access the Quote object / create one.

Then if you look into Magento\Quote\Model\Quote, there's a method call addProduct:

public function addProduct(
        \Magento\Catalog\Model\Product $product,
        $request = null,
        $processMode = \Magento\Catalog\Model\Product\Type\AbstractType::PROCESS_MODE_FULL
    ) 

You can also look into the content of that function to see how a product object is used to create a quote item object.

0

This is simple order create script, it might helps you

<?php    
use Magento\Framework\App\Action\Action;

class OrderCreateTest extends Action {
    protected $_quoteFactory;
    protected $_orderModel;
    protected $_productModel;
    protected $_customerRepository;
    protected $_quoteManagementModel;

    public function __construct(
        \Magento\Quote\Model\QuoteFactory $quoteFactory,
        \Magento\Sales\Model\Order $orderModel,
        \Magento\Catalog\Model\Product $productModel,
        \Magento\Framework\App\Action\Context $context,
        \Magento\Quote\Model\QuoteManagement $quoteManagementModel,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
    ) {
        $this->_quoteFactory         = $quoteFactory;
        $this->_orderModel           = $orderModel;
        $this->_productModel         = $productModel;
        $this->_customerRepository   = $customerRepository;
        $this->_quoteManagementModel = $quoteManagementModel;

        parent::__construct($context);
    }

    public function execute() {
        try {
            $customerId = $storeId = 1;
            $customer   = $this->_customerRepository->getById($customerId);
            $quote      = $this->_quoteFactory->create();
            $product    = $this->_productModel->load(1);

            $quote->setStoreId($storeId);
            $quote->assignCustomer($customer);
            $quote->addProduct($product);
            $quote->setCustomerEmail('roni_cost@example.com');

            $addressData = [
                "firstname"  => "Test",
                "lastname"   => "Test",
                "street"     => "Sample Street 10",
                "city"       => "Somewhere",
                "postcode"   => "123456",
                "telephone"  => "123456",
                "country_id" => "US",
                "region_id"  => 12, // id from directory_country_region table
            ];

            $billingAddress  = $quote->getBillingAddress()->addData($addressData);
            $shippingAddress = $quote->getShippingAddress()->addData($addressData);

            $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                            ->setShippingMethod('flatrate_flatrate')
                            ->setPaymentMethod('checkmo');

            $quote->getShippingAddress()->setShippingMethod('flatrate_flatrate');
            $quote->setPaymentMethod('checkmo');
            $quote->getPayment()->setQuote($quote);
            $quote->getPayment()->importData(['method' => 'checkmo']);
            $quote->setInventoryProcessed(false);
            $quote->save();

            $order = $this->_quoteManagementModel->submit($quote);

            echo "<pre>ORDER DATA";
            echo $order->getId();
            exit;

            exit;
        } catch (\Exception $ex) {
            echo $ex->getMessage();
            exit;
        }
    }
}
  • No, this is not what I was asking for. Please read the title of the question, I want to add product to existing order, not create new order. – b_pcakes Jun 24 '16 at 17:21
0
//$order - your order object        
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $orderItem = $objectManager->create('Magento\Sales\Model\Order\Item');
         $orderItem->setProductId($product->getId());
                $orderItem->setSku($sku);
                $orderItem->setQtyOrdered($qnt);
                $orderItem->setBasePrice($product->getPrice());
                $orderItem->setPrice($product->getFinalPrice());
                $orderItem->setRowTotal($product->getFinalPrice());
                $orderItem->setOriginalPrice($product->getPrice());
                $orderItem->setProductType($product->getTypeId());
                $order->addItem($orderItem);
                try {

    // \Magento\Sales\Model\ResourceModel\Order $orderResource,

                    $this->orderResource->save($order);
                }
          catch (\Exception $e) {
                    throw new \Magento\Framework\Exception\LocalizedException(
                        __($e->getMessage() . " for order {$order->getIncrementId()}")
                    );
                }
  • This will not change the order totals. So its not recommended to do this way. – Senthil Kumar Muppidathi Sep 12 '17 at 5:42
  • @SenthilKumarMuppidathi it depends on goals – bxN5 Sep 18 '17 at 8:40
  • you are right but I think as a tech guy we also need to look at data sanity which may potentially have an impact later on. – Senthil Kumar Muppidathi Sep 23 '17 at 2:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.