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

juliadave (not verified)

I merely hit upon this web site and desired to enunciate that I've definitely delighted in reckoning your blog articles or blog posts. Rest assured I'll subsist https://www.assignmentcloud.co.uk/write-my-assignment pledging to your RSS and I wish you write-up after much more shortly

dave (not verified)

thanks for sharing it to each one of us. Looking forward to more information and you have continually intrigued me. Thank you for creating an https://www.uhjackets.com/blade-runner-2-ryan-gosling-leather-fur-coat
article that has amazing substance and is well formed and even I am revived by your composed style as well.

Add new comment