Tag Archives: drupal commerce order create

How to create a order In Drupal programmatically

Today I got one strange requirement from my client and that is he has a Drupal website which is combined with NetSuite(NS), and he wants that if he create any order at NS end then this order will be create at Drupal end using web-services. So now the first question  “How to create a order In Drupal programmatically”.

Following are the steps:

Step1: Create an new order with the help of below code:

// Create the new order in checkout status.
$order = commerce_order_new($uid, 'pending');

Step2: Load products which you want to add in your news order with the help of below code:

$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id, array());
commerce_line_item_save($line_item);

Note: You can do the same for multiple products in a single order.

Step3: Wrap up the order with the help of below code:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

Step4: Save the order to database:

commerce_order_save($order);

Step5: Done :)

Code together:

$uid = 'USER_ID';
$product_id = 'PRODUCT_ID';

$order = commerce_order_new($uid, ‘pending’);

$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id, array());
commerce_line_item_save($line_item);

$order_wrapper = entity_metadata_wrapper(‘commerce_order’, $order);
$order_wrapper->commerce_line_items[] = $line_item;

commerce_order_save($order);

Summery:

Create one link using hook_menu() and call a custom ‘page callback’ function and add the above code in this custome function and execute the newly created link in browser.