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(),
// You can set the quantity with setQuantity.
// You can also set the price with setUnitPrice.
$unit_price = new  \Drupal\commerce_price\Price('9.99', 'USD');
// 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.
// 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' => '', // The email address for the order.
  'uid' => 1, // The user id the order belongs to.
  'ip_address' => '', // 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.
// You can also add order items to an order.

Hey! Don't miss a new cool stuff!


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 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
article that has amazing substance and is well formed and even I am revived by your composed style as well.

Barrett (not verified)

Drupal 8 has made so many things easier for us to do, man. As someone who works at the essay service uk site, it's certainly the best software to use right now. If you have any problems with that statement, I'd like to know why.

Add new comment