One thing I found lacking with Drupal Commerce was the lack of tokens with line-item level data. I wanted to send an email via Rules to the site’s managers with order/product information (no billing of course). There was nothing that listed product/line items. Here is what I used to get what I needed.
You will see some custom formatting I have in place that creates an output string. These tokens will then be accessible in Rules in other areas that use tokens.
/**
* Implements hook_token_info_alter().
*/
function mymodule_token_info_alter(&$info) {
$info['tokens']['commerce-order']['billing-details'] = array(
'name' => t('Billing Details token'),
'description' => t('Custom billing details token.'),
);
$info['tokens']['commerce-order']['product-details'] = array(
'name' => t('Product Details token'),
'description' => t('Custom product details token.'),
);
}
/**
* Implements hook_tokens().
*/
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
$url_options = array('absolute' => TRUE);
if (isset($options['language'])) {
$url_options['language'] = $options['language'];
$language_code = $options['language']->language;
}
else {
$language_code = NULL;
}
$sanitize = !empty($options['sanitize']);
$replacements = array();
if ($type == 'commerce-order' && !empty($data['commerce-order'])) {
// get order details
$order = $data['commerce-order'];
$profile = commerce_customer_profile_load($order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id']);
$customer = $profile->commerce_customer_address[LANGUAGE_NONE][0];
$total = $order->commerce_order_total[LANGUAGE_NONE][0]['amount'] . $order->commerce_order_total[LANGUAGE_NONE][0]['currency_code'];
foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item) {
$items[] = commerce_line_item_load($line_item['line_item_id']);
}
// add output to tokens
foreach ($tokens as $name => $original) {
switch ($name) {
case 'billing-details':
$replacements[$original] = $customer['name_line'] . "\n" . $customer['thoroughfare'] . "\n" . $customer['premise'] . "\n" . $customer['locality'] . ', ' . $customer['administrative_area'] . ' ' . $customer['postal_code'] . "\n\n";
break;
case 'product-details':
$output = '';
foreach ($items as $item) {
$output .= number_format($item->quantity) . ' ' . $item->line_item_label . ' - ' . $item->commerce_total[LANGUAGE_NONE][0]['amount'] . $item->commerce_total[LANGUAGE_NONE][0]['currency_code'] . "\n";
}
$replacements[$original] = $output . "\nOrder total: " . $total . "\n";
break;
}
}
}
return $replacements;
}