Tags/topics: 
1
Answers
Vote up!
0
Vote down!

Commerce product bundles with one or more products to cart

How can we add a commerce bundle with corresponding subproducts to cart by progrmatically.

Asked by: saranya
on July 30, 2015

1 Answer

Vote up!
0
Vote down!

Using Entity Metadata Wrappers, you could create an "Order" entity, add a line item from the result of the function:

<?php
// Original code from: <a href="https://commerceguys.com/blog/creating-orders-drupal-commerce-api
//">https://commerceguys.com/blog/creating-orders-drupal-commerce-api
//</a> Original Author: Ryan
// Modifications by Josh
global $user;
$product_id = 6;
 
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid, 'checkout_checkout');

// Save the order to get its ID.
commerce_order_save($order);
 
// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Possibly replace with ... (but you would need a lot more variables)
//$line_item = commerce_bundle_product_line_item_new($product, $bundle_item, $group, $bundler, $quantity = 1, $order_id = 0, $data = array(), $type = 'commerce_bundle_line_item')

// Save the line item to get its ID.
commerce_line_item_save($line_item);
 
// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

dpm($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
//drupal_goto('checkout/' . $order->order_id);
?>

Or something like that. The more I dig into the code of the commerce_bundle, the more I'm perplexed. It may be that you can't do this without understanding Form API more than I do personally.

Josh

Josh Miller
Answer by: Josh Miller
Posted: Aug 5, 2015