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.

2 thoughts on “How to create a order In Drupal programmatically

  1. I am using exactly same code for creating an order. But somehow wrong product is getting added to my order when i look at it from frontend. I have checked ‘productid’ and ‘productobject’ to be correct before creating the line item. Also the line_item_label value is correct in ‘commerce_line_item’ table. But still when i view my order, it always shows me same Title(wrong one).
    Any hints/suggestions are appreciated.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>