Discussions

Programmatically add a donation

I've followed the great screencast:
http://www.commerceguys.com/resources/articles/238
to add a donation feature to a drupal commerce site.
I know need to be able to add a donation programmatically (this is just a toy example if someone is interested in my real worl case let me know).
I've managed to do it with the following code but It is probably not the best approach as it is quite "brute force". It works but any pointers of the correct way to do this are welcomed.
Here is the code:

<?php
 
global $user;
 
// load the order, create new one if unexisting
 
if (!$order = commerce_cart_order_load($user->uid)) {  $order = commerce_cart_order_new($user->uid);
  }

 
// Define the values for the product containing the line item
 
$product_id=4;
 
$quantity=1;
 
$product = commerce_product_load($product_id);

 
// Wrap the order for easy access to field data.
 
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

 
// Invoke the product prepare event with the shopping cart order.
 
rules_invoke_all('commerce_cart_product_prepare', $order, $product, $quantity);

 
// Create a new line item ot type product
 
$line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);

 
// Hardcode the line item and donation amount
 
$line_item->type='donation';
 
$line_item->line_item_label='Donation';
 
$line_item->field_donation_amount['und'][0]['value']=10;
 
$line_item->data['context']['product_ids'][0]=4;
 
$line_item->data['context']['add_to_cart_combine'] = 1;
 
$line_item->data['context']['display_path'] = 'node/4';
 
$line_item->data['context']['entity']['entity_type']='node';
 
$line_item->data['context']['entity']['entity_id']=4;
 
$line_item->data['context']['entity']['product_reference_field_name']='field_product';
 
// Change the display path to one of our special form
 
$line_item->commerce_display_path['und'][0]['value']='miformularioe';
 
$line_item->commerce_display_path['und'][0]['format']='';
 
$line_item->commerce_display_path['und'][0]['safe_value']='miformularioe';

 
// Process the unit price through Rules so it reflects the user's actual
  // purchase price.
 
rules_invoke_event('commerce_product_calculate_sell_price', $line_item);

 
// Save the line item now so we get its ID.
 
commerce_line_item_save($line_item);

 
// Add it to the order's line item reference value.
 
$order_wrapper->commerce_line_items[] = $line_item;
 
// Save the updated order.
 
commerce_order_save($order);
?>
Posted: Feb 12, 2012

Comments

muschpusch on April 9, 2012

There is the fantastic commerce_example module and in there you will find some examples around creating line items and orders from code. I'm not sure if you need to trigger the rule events but the code looks good!