How to create an Order and Order item in Drupal commerce for Drupal 8

Posted by admin on Wed, 01/17/2018 - 10:20

Code snippet to create an Order and Order Items in Drupal Commerce for Drupal 8.

$order_item = \Drupal\commerce_order\Entity\OrderItem::create([
  'type' => 'product_variation', // The default order item type is 'product_variation' which references the product variation purchasable entity type.
  'purchased_entity' => $variation, // The product variation we created above.
  'quantity' => 2,
  'unit_price' => $variation->getPrice(),
]);
$order_item->save();
 
// You can set the quantity with setQuantity.
$order_item->setQuantity('1');
$order_item->save();
 
// You can also set the price with setUnitPrice.
$unit_price = new  \Drupal\commerce_price\Price('9.99', 'USD');
$order_item->setUnitPrice($unit_price);
$order_item->save();
 
// Next we create the billing profile.
$profile = \Drupal\profile\Entity\Profile::create([
  'type' => 'customer',
  'uid' => 1, // The user id that the billing profile belongs to.
]);
$profile->save();
 
// Next, we create the order.
$order = \Drupal\commerce_order\Entity\Order::create([
  'type' => 'default', // The default order type is 'default'.
  'state' => 'draft', // The states for the default order type are draft, completed, canceled
  'mail' => 'user@example.com', // The email address for the order.
  'uid' => 1, // The user id the order belongs to.
  'ip_address' => '127.0.0.1', // The ip address the user ordered from.
  'order_number' => '6', // Sets the order number. If left out, will use the order's entity ID.
  'billing_profile' => $profile, // The profile we just created.
  'store_id' => $store->id(), // The store we created above.
  'order_items' => [$order_item], // The order item we just created.
  'placed' => time(), // The time the order was placed.
]);
$order->save();
 
// You can also add order items to an order.
$order->addItem($order_item);
$order->save();
×

Hey! Don't miss a new cool stuff!

Comments

Anonymous (not verified)

I have a hard time describing my thoughts on content, but I really felt I should here. Your article is really great. I like the way you wrote this information. running assessment Glasgow

Anonymous (not verified)

I concede, I have not been on this page in quite a while... on the other hand it was another happiness to see It is such an imperative subject and disregarded by such a large number of, even experts. experts. I thank you to help making individuals more mindful of conceivable issues. http://www.uni-protokolle.de/foren/viewt/320971,0.html

Anonymous (not verified)

You know your activities emerge of the group. There is something exceptional about them. It appears to me every one of them are truly splendid! Exclusive Escorts

Add new comment