Drupal Commerce: Dynamic Line Item Titles
HOWTO: Dynamically create a line_item title based off the node product display from which it was added to cart.
I'm currently creating a site which will enable it's readers to purchase Job Listings. I've decided to use Drupal 7 & Drupal Commerce for this.
I've created a Job Listing node type, then created three products (30 day, 60 day & 90 day listings) and then associated each of these products to my Job Listing node via a product reference. This makes my Job Listing node purchasable. Perfect.
The problem is because I'm doing it like this, when a reader adds a 30 day listing to his cart, the line item title is simply 30 days. This isn't very descriptive. I thought I'd be able to pull in the data from views, but currently the node product display (while it's associated) is not exposed in views. I'm in the issue queue trying to get this feature added.
So I need another way to dynamically create a title for my line_item. There are a couple hooks that can do this, but only one is the correct way. None of these hooks are currently documented, so I'll list them in case you're interested.
- hook_commerce_line_item_update($line_item);
- hook_commerce_line_item_presave($line_item);
- hook_commerce_line_item_type_info_alter(&$line_items);
The proper way to do it would be to use hook_commerce_line_item_type_info_alter(&$line_items);
Here's the code
<?php
function mymodule_commerce_line_item_type_info_alter(&$line_items) {
$line_items['product']['callbacks']['title'] = 'mymodule_line_item_title';
}
function mymodule_line_item_title($line_item) {
return t('!title (!product)', array(
'!product' => commerce_product_line_item_title($line_item),
'!title' => $line_item->data['display_uri']['options']['entity']->title
));
}
?>So that's how you properly create dynamic line item titles in Drupal Commerce.
There's a limitation though, if your reader adds the same product from multiple node displays in the cart (since they're the same product) they'll get added under the first item's title with a quantity of 2. Here I've explained how to add the same product to your cart under seperate line items using Drupal Commerce.
Comments
Thanks!