3

I'm sending confirmation message of a commerce order via Message Notify. I want to display the selected shipping service in the email.

3

Assuming that you are using Commerce Message module for this.

One way to do this is by adding your own token. In your custom module (MYMODULE) add this code (I have too many comments just for educational reasons):

// Set arguments for our custom token !order-shipping
function MYMODULE_message_presave($message) {
  if (!empty($message->mid)) {
    return;
  }
  $message->arguments['!order-shipping'] = array(
    'callback' => 'commerce_message_order_shipping',
    'pass message' => TRUE,
  );
}

/**
 * Message callback; Show Order Shipping Service label (!order-shipping).
 *
 * @param $message
 *   The Message entity.
 */
function commerce_message_order_shipping(Message $message) {
  $wrapper = entity_metadata_wrapper('message', $message);
  // Get order id from current commerce message
  $order_id = $wrapper->message_commerce_order->getIdentifier();
  // Get order from order_id
  $order_wrapper = commerce_order_load($order_id);
  // Get the line items. Shipping service is a line item (like product, discount etc)
  $line_items = $order_wrapper->commerce_line_items['und'];

  // Loop through the line items so you find the shipping service
  foreach ($line_items as $delta => $line_item_wrapper) {
    $line_item_id = $line_item_wrapper['line_item_id'];
    $line_item = commerce_line_item_load($line_item_id);
    //dpm($line_item);
    if(isset($line_item->commerce_shipping_service)) {
      // This is want we need, the shipping service label
      $shipping_service = $line_item->line_item_label;
    }
  }

  return $shipping_service;
}

Then in your message body add you new token !order-shipping.

Notice that this method works for other line items too... Also, it works for other modules that send emails (such as commerce_email) but with some difference in the hook function - currently hook_message_presave($message) -.

Credits to this issue: http://drupalcommerce.org/node/10096

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.