Dec 03 2014
Dec 03

We had a Drupal project, implementing a commerce site for a local store. We use Drupal Commerce, as always, for this type of websites. You may see that we have alot of Drupal Commerce themes on our portfolio.

During the project, there was a minor request from our customer: add the Continue Shopping button to the cart. This feature is available on Ubercart, especially for Drupal 6 Ubercart users. Most of ecommerce sites have this feature as well. But it is not built-in with Drupal Commerce.

As I searched on the issues, I found a very helpful thread: Continue shopping in cart. Zorroposada presented a custom code to achieve it:

* Implements hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)
function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
$form['actions']['continue_shopping'] = array(
'#type' => 'button',
'#value' => t('Continue Shopping'),
'#weight' => -999,
if (isset($_SERVER['HTTP_REFERER']) && strlen($_SERVER['HTTP_REFERER'])) {
// if user comes from product detail page, redirect user to previous page
$form['actions']['continue_shopping']['#attributes'] = array('ONCLICK' => "history.go(-1); return false;");
} else {
// redirect user to product list page 'store' by default
$form['actions']['continue_shopping']['#attributes'] = array('ONCLICK' => "window.location.href='" . url('store') . "'; return false;");

I do nothing better here. I just wrap this code on a custom module, so any lazy users can just download and install it.

The module is called "Commerce Continue Shopping", and you will find it in the Other section of the Drupal module page when unzip it to /sites/all/modules. Enable it and you will see the Continue Shopping button on your cart.

Pls download the module here:

Apr 28 2014
Apr 28

Sometimes you want to license files without people needing to purchase them. Even using coupon codes to make products free still requires them to be purchased through the Commerce Checkout system.

This is fine for physical products where you still want email and address details of potential future clients.

However when it comes to files, users require an account to access their files, so chances are you have all the details for them already. And there is no shipping required so why make them go through the checkout process just to get a license for a free file? (Seriously if you have reasons comment!)

Here is a snippet of how to generate a file license for a user:


Grammar Lesson:

Today I learnt the difference between 'license' and 'licence'. Unless you are American (in which case just ignore the existence of 'licence') read this.

May 23 2013
May 23

Episode Number: 


In this episode we continue learning about Drupal Commerce and dive into some of the layout aspects of building out Drupal Commerce product displays.

In this episode you will learn:

  • How to modify the layout of a Drupal Commerce product display
  • How fields are used to control the Drupal Commerce product display layout

DDoD Video: 

May 19 2013
May 19

Exaltation of Larks will be at DrupalCon Portland next week and we’d like to share some of our DrupalCon plans.

To summarize, we’re excited to announce that we’re co-training on Drupal Commerce with Commerce Guys; we’re continuing the conversation we started last month about Long Term Support for Drupal 6; and we have a quick list of Drupal Fit activities that are happening before and during the conference.

Interested? Read on.

Drupal Commerce Training

One of our core philosophies is that high-quality trainings are one of the very best ways to help Drupal and the Drupal developer community grow, and we’ve been working closely with Commerce Guys for the DrupalCon training, Launching an Online Store with Commerce Kickstart, on Monday, May 20th.

Our joint curriculum is based on the 7.x-2.7 version of Commerce Kickstart, which was just released yesterday. The attendees of this training are really in for a treat and this is a Commerce training that’s not to be missed.

Drupal Commerce Meetups Every Month

This is a good time as any to let everyone know that we’re proud sponsors of the Drupal Commerce Meetup, which meets in Los Angeles on the 4th Tuesday of each month.

Not in Los Angeles? Not to worry, these meetups are also being broadcast online for everyone to tune in for and enjoy. The next meetup is after DrupalCon on Tuesday, May 28th, so be sure to sign up over at Drupal Groups to hear what the next meetup is about.

These meetups are recorded and the video from last month’s meetup is available online. The video features a presentation by Ryan Szrama on Relify and personalized product recommendations. Relify neatly narrows the gap between Drupal Commerce and recommendation systems, like Amazon’s “you may also like” suggestions.

Long Term Support (LTS) for Drupal

We’re hosting a BoF (birds of a feather) discussion on long-term Drupal support (particularly for Drupal 6 sites when Drupal 8 comes out and bug fixes and security releases for Drupal 6 are discontinued).

Long Term Support is a topic that is near and dear to us and a number of our clients and this BoF is a followup to our earlier post, Drupal 6 End of Life When Drupal 8 is Released… Or Not.

We’re preparing an “LTS” version of Drupal 6 and have a lot more planned, so stay tuned to the DrupalCon BoF schedule and @LarksLA on Twitter for news of when this BoF gets scheduled.

Drupal Fit

Finally, if you haven’t heard of Drupal Fit, it’s a group of nearly 200 Drupaleros who are dedicated to fitness is one form or another (mental, physical, etc.) and to sharing their experiences with other Drupal community members.

Here’s a summary of some of the Drupal Fit activities at DrupalCon Portland.

Are there any other Drupal Fit activities not mentioned here? Send @DrupalFit a shout out on Twitter.

read more

May 17 2013
May 17

Episode Number: 


In this episode we continue learning about Drupal Commerce and begin learning how to set up Drupal Commerce Product Attributes using Drupal Taxonomy.

In this episode you will learn:

  • How to set up Drupal taxonomy vocabularies and taxonomy terms to use as product attributes.
  • How to add Taxonomy term reference fields to Product types to create Drupal Commerce product attributes.

DDoD Video: 

Apr 15 2013
Apr 15

Episode Number: 


Learn how to set up a Drupal Commerce product display for displaying ecommerce products on your Drupal 7 Drupal Commerce website.

In this episode you will learn:

  • How to create a Drupal Commerce Product display content type
  • How to add Drupal Commerce products to a cart

DDoD Video: 

Apr 11 2013
Apr 11

Episode Number: 


Learn how to create and manage Drupal Commerce Product Types on your Drupal 7 ecommerce website.

In this episode you will learn:

  • How to create a Drupal Commerce Product Type
  • How Drupal Commerce Product Types fit into the overall ecommerce website
  • How to add product images to a Drupal Commerce Product Type

DDoD Video: 

Apr 10 2013
Apr 10

Episode Number: 


This episode goes over a basic overview of Drupal Commerce and how it can be used to create a Drupal 7 based ecommerce website.

In this episode you will learn:

  • What is Drupal Commerce
  • How Drupal Commerce can be used to build flexible and dynamic ecommerce websites
  • Common Drupal Commerce terminology

DDoD Video: 

Mar 30 2013
Mar 30

Few month ago I developed  a simple module called Commerce Order2pdf and then I also added custom tokens as you can read from this post Custom token creation for Drupal 7 and now I reviewed this module a bit and planned to add views field handler (This means I can create custom view with download links). 

So how did I implemented this?

First step was to edit commerce_order2pdf.module file and add hook_views_api. So I could start working with views.

 * Implements hook_views_api().
function commerce_order2pdf_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'commerce_order2pdf') . '/includes/views',

Next one was to create subdirectories includes/views into my commerce_order2pdf folder (module folder).

After this I had to tell views about my data structure.
So I did created new file /includes/views/ and added hook_views_data.

 * Implements hook_views_data()
function commerce_order2pdf_views_data() {
  $data = array();
  $data['commerce_order']['order2pdf_link'] = array(
    'field' => array(
      'title' => t('Download pdf order'),
      'help' => t('Provide a simple link to download the order.'),
      'handler' => 'commerce_order2pdf_handler_field_order_pdf_link',
  return $data;

In this array I did extended commerce_order group and added field handler class callback.

Now we will add a new file to includes/views folder.

 * Field handler to present an order pdf download link.
class commerce_order2pdf_handler_field_order_pdf_link extends commerce_order_handler_field_order_link {
  function construct() {

  function render($values) {
    $order = commerce_order_new();
    $order->order_id = $this->get_value($values, 'order_id');
    // Add hash key for a download link.
    $hash = hash('md5', $order->order_id . $values->commerce_order_created);

    $text = !empty($this->options['text']) ? $this->options['text'] : t('Download');
    return l($text, "order2pdf/{$order->order_id}/{$hash}");

My last step is to say Drupal about these files in

For this step I will just add two rows to my .info file. 

files[] = includes/views/
files[] = includes/views/

Now you can add views download field to your view. (If you make thses changes after you enabled your module then you can just clear caches and it will work).

Edit 13. April 2013 
Just found a good videos

[embedded content]

[embedded content]

Nov 06 2012
Nov 06

Few days ago my client came and said.. I need to exlude a shipping when there's special type of product.
At first I was sure this can be done with rules but it didn't work out for me.
So after spending some time with this I wrote some php.
At first I would like you to know. Its not good idea to put some php throught the database, becouse it will make your site at least a bit slower. But still my client needed this really fast so I did it.
At first from the shipping options I choosed configure component and added new condition wich was a PHP.

# Get all the line item ids from the order.
$line_item_ids = $commerce_order->commerce_line_items[LANGUAGE_NONE];
$line_items = commerce_line_item_load_multiple($line_item_ids);
# If the line item is the type of product then add this to array.   
foreach($line_items as $line_item) {
  # Put all the product types the array.
  if(isset($line_item->commerce_product[LANGUAGE_NONE][0]['product_id'])) {
      $product_ids[] = $line_item->commerce_product[LANGUAGE_NONE][0]['product_id'];
$products = commerce_product_load_multiple( $product_ids);
foreach($products as $product) {
  $types[] = $product->type;
# If the product type (tops) is in array then return true.
if (in_array('tops', $types)) {
   return TRUE;

After I just added if this is is true then negate. This could be easily used other ways. Lets say you want to do something if theres this type of procuct in the shppping cart.

Oct 11 2012
Oct 11

 Today I had a plan to create tokens for my new module wich will create hashed pdf link for commerce order, becouse it would be really nice to use tokens with rules. So I just looked how it works and wanted to create some simple examples.
I can easily create new token from scratch with these two functions.

 * Implements hook_token_info_alter().
function commerce_order2pdf_token_info() {
  $info['tokens']['commerce-order']['hashed_pdf_link'] = array(
    'name' => t('Hashed link to pdf'),
    'description' => t("Hashed link for pdf generation."),
  return $info;
 * Implements hook_tokens().
function commerce_order2pdf_tokens($type, $tokens) {
 if($type = 'commerce-order') {
   $replacements['[commerce-order:hashed_pdf_link]'] = 'my replacement';
  return $replacements;

What I really want to do is to add new tokens to my existing tokens and use existing data. So I just had to use hook_token_info_alter and hook_token_alter functions.

 * Implements hook_token_info_alter().
function commerce_order2pdf_token_info_alter(&$data) {
  $data['tokens']['commerce-order']['hashed_pdf_link'] = array(
    'name' => t('Hashed link to pdf'),
    'description' => t("Hashed link for pdf generation."),
  return $data;
 * implements hook_tokens_alter().
function commerce_order2pdf_tokens_alter(array &$replacements, array $context) {
  $order = $context['data']['commerce-order'];
  $hash = hash('md5', $order->order_id . $order->created);
  $replacements['[commerce-order:hashed_pdf_link]'] =  l(t('Download order as pdf'),
"order/{$order->order_id}/" . $hash, array('absolute' => TRUE));
Apr 17 2012
Apr 17

The second Drupal Commerce session I attended was presented by another member of the Commerce Guys team, Pedro Cambra.  Pedro co-maintains several major Commerce contrib modules such as commerce feeds, commerce, Commerce Reorder and Commerce Extra Panes.

Many of these modules, while not technically required for the operation of a online store, make the online experience much better.  For example Commerce Reorder allows users to create a new order using the contents of an existing order.  For B2B online commerce, this is a killer feature, since many businesses order the same set of products over and over again.  Commerce VBO Views brings Views Bulk Operations into commerce, making mass deletion of products, profiles, and orders possible, this makes unclogging the order queue as easy as cleaning out old nodes from the content section.

Importing content from another system is a particularly thorny challenge.  Luckily there exists a pair of solutions for this issue.  Whether you're a Migrate or a Feeds user, Drupal Commerce has a module that imports data into Commerce automatically. One commerce contrib module that I have a particular fondness for is the Commerce Feeds module.  This leverages the feeds module, which takes a feed in an XML, RSS or CSV format and turns the data into products.  The feeds are exportable via features and new products can be added automatically as they're created.  This obviates the need to manually import products into Drupal Commerce.  Commerce Migrate takes a similar approach, but utilizes the Migrate module to create the product entities.

Another neat Commerce contrib module is the Commerce Physical module, which utilizes the Physical Fields module to give products physical characteristics such as dimensions and weight.  These can be used in shipping calculations to return the exact shipping cost calculated by courier APIs.  

Payment methods are probably the most important aspect of eCommerce.  Drupal Commerce has this particular part in spades.  The payment method modules run the gamut from PayPal to Purchase Order, and everything in between.

There also exists Commerce Contrib wishlists that adds a 'Add to Wishlist' button to products, coupons that offer discounts, addressbook that simplifies the checkout process, multi-currency support for international commerce, and so much more.

The Commerce sessions were just a few of the amazing and wildly varied panoply of concepts, companies and community that is DrupalCon.

It was quite the experience, especially with the backdrop of the sunshine and the warm weather.  I loved being able to introduce myself to people I've only met in IRC previously, and reconnecting with old Drupal buddies.

As said previously, this was my first DrupalCon and I was very happy to have gone. I now having a greater idea of the depth of the passion and the breadth of the community.  It's pretty amazing to pass groups of people between sessions speaking so many languages and yet, they're all talking about the open web, and Drupal's role in that ecosystem.  I've always been a big fan of Drupal, but going to DrupalCon has definitely added to that appreciation.

Apr 12 2012
Apr 12

Going to DrupalCon Denver was a welcome break from the cold and gloom of a northwest spring. The Rocky Mountain sunshine provided a backdrop for the largest DrupalCon on record.

This DrupalCon was especially notable since it was my first opportunity to attend in person. I've made it a point in the past to watch the keynotes, especially Dries, as close to real time as possible. As well as jealously following the Twitter feeds of those in attendance to glean any breaking news from the forefront of the Drupal community. As expected, there were too many good sessions to choose just one to attend.

One particular track that caught my attention was the eCommerce track. For sometime I've felt that Drupal's greatest untapped potential was in this sphere and it was a welcome change to see eCommerce receive the kind of attention given to other Drupal application classes. To complete my excitement for this particular track, I noted Ryan Szrama's Drupal Commerce session on Wednesday Morning. As a project lead for the very popular Drupal commerce project and long time Drupal eCommerce guru, sitting in on this session was my chance to get a sneak peak at arguably the fastest growing sector of Drupal.

All about Commerce

For a 30 second introduction to Drupal Commerce, it's important to know the past. Drupal Commerce grew out of UberCart, a highly successful set of eCommerce modules for Drupal 6, it provided a simplified eCommerce solution.

Shortly thereafter, Ryan Szrama started a new project, that expanded the horizons of eCommerce in Drupal. New to Drupal 7 was the concept of entities. Objects that behaved like nodes, but could be displayed and manipulated more flexibly.

Furthermore, entities could have fields placed upon them, and thus the Commerce concepts of using entities as components in a commerce website was born. With entities, products could be freely displayed privately, abstracting the stock keeping and managerial facets of commerce away from the display side. In addition, products could be uniquely identified by a Stock Keeping Unit or SKU, in Drupal much in the same way products are tracked by SKU in warehouses.

Since entities could be referenced in a node, creating a display page became as simple as creating a product display node and referencing the products that belonged to that particular display. Whereas UberCart was designed as a starter store in a box, more of a plug and play solution. Drupal Commerce provided a more fully customizable framework, that allows businesses to modify the framework to fit their particular business model. Drupal Commerce was designed to leverage the full potential of Drupal 7 for power and flexibility. 

As a framework, Commerce core is as lean as possible, so much so that the Commerce shipping module doesn't even ship with Commerce core. The rationale is that not all stores have physical products that need to be shipped. As a side note, there exists a Commerce shipping module, maintained by the same crew that work on Commerce core, that is easily download-able for shipping physical products. Since commerce is so flexible, there exists a myriad of neat and, possibly, ready to use solutions for nontechnical users. Contributed modules such as a wish-list, reorder functionality and stock keeping extend the power of commerce and make it easier for those new to Drupal and Commerce to utilize these resources, with the end result of increasing the adoption of the Drupal Commerce framework.

What's next in Commerce

While Drupal Commerce is receiving a lot of attention for the flexibility of the framework. The learning curve can be a little steep, especially for those new to Drupal.

One of the main initiatives to be undertaken by Commerce Guys to help increase adoption is to increase the overall amount of documentation, with a focus on how to do basic tasks like calculate a tax rate or how to create a discount for certain customers. There exists a fair amount of documentation both in the form of step by step guides and in screen-casts or video format.

Another sticking point in using Drupal Commerce is the lack of a clear, easy to use UI. One of the powerful things about Drupal Commerce is that it's built on existing Drupal tools and infrastructure. One such example is the pervasive use of the Views and Rules contrib modules that make it easy to create and customize data displays of products, shopping carts and lists of line items. The catch with using some of the more complex sets of contrib modules is that in order for store administrators to make simple changes, they must first learn the basics of things like Views.

One perfect example of this would be where a store administrator, someone who normally uses the middle part of the site to administer transactions, needs to adjust the percentage of a discount. This discount might be offered to individuals who purchase more than a set cost of items. Editing the discount amount requires no less than diving three levels into the commerce product pricing rules interface and then an additional two levels via the Rules interface directly. While this might be a trivial task for a lifelong Drupalista, for someone more at home in a WYSIWYG editor, this could be scary and confusing.

The aim is to make simple tasks that site managers do regularly more straightforward. That having a familiarity with Drupal not be a requirement for administering a Drupal Commerce site. In short, to drive adoption of the Drupal CMS via Commerce installs by introducing people to Drupal as a course of building a Commerce site.

To help accelerate the adoption of Commerce another initiative is to release a new version of Commerce Kickstart. Commerce Kickstart is an introductory install profile containing a basic store, with a trio of example products, an example payment method and not much else. In my experience I've used it more as a testing suite or a playground to get a feel for what Commerce is and what it can offer me in terms of tools and examples to build a commerce setup for a client. This focus on developers was helpful to me, but probably isn't for someone looking to setup a small eCommerce site with little to no custom code.   This will no long er be the case for Commerce Kickstart 2.0, who's focus will be squarely on site builders.

In that vein, Commerce Kickstart 2.0 will be redesigned from the ground up. Commerce core, by design, lacks anything not considered absolutely essential for eCommerce. This includes things like shipping, since not all stores sell physical products. However, Commerce Kickstart 2.0 will have the shipping module built in.

One other sticking point is appearance. Again as Drupalistas, we're used to seeing an unthemed site, something in perhaps in Bartik or maybe even -gasp- Garland. That said, the rest of the world may not share this understanding view of Drupal's theme layer. As such, Commerce Kickstart 2.0 will have its own Omega based sub theme that would function as an introductory theme for people just looking to get an eCommerce site up and running as quickly as possible.

To make this even more exciting, Commerce Guys has of pledged to release Commerce Kickstart 2.0 by DrupalCon Munich this August, quite the ambitious time line.

Needless to say I'm very excited in the direction Drupal Commerce is taking, I'd love to see Drupal take off in the eCommerce, much in the same way it has taken off in government and the NGO space. 

Mike Nielson - nielsonm

Mar 01 2012
Mar 01

Get started with e-commerce in Drupal 7

Drupal Commerce videos are here! People have been asking for them for a while now, and we've been working hard to get them ready. In this Drupal Commerce series, Ryan Szrama takes you through the process of creating your own Drupal e-commerce site using Drupal Commerce for Drupal 7. The series starts by getting the basics installed with the Commerce Kickstart project, and then works through working with products, taxes, discounts, checkout, and general configuration of our store. We have two of the videos available for free, so you can see what we will be covering and get into the details of how to add product displays to your store, and understand how they are different from the products themselves.

Drupal Commerce relies heavily on the Views and Rules modules for many of its features, which allow you a lot of customization. If you need a refresher on these two modules, you can watch these other Drupalize.Me series:

Feb 22 2012
Feb 22

We kick off the Commerce Basics series with a look at the LB Robotics store site that we will be building. Ryan gives a quick tour of the site and discusses the main topics we will be focusing on, like products, taxes, discounts, checkout, and general configuration of our store.

Drupal Commerce relies heavily on the Views and Rules modules for many of its features, which allow you a lot of customization. If you need a refresher on these two modules, you can watch these other Drupalize.Me series:

Feb 22 2012
Feb 22

Now that we have created our products we'll dive into the Product display content type so that we can display our products to our users. In this instance we'll start out be re-using the nodes created by Commerce Kickstart, then we create two new displays for our remaining items. We finish up by rearranging the fields on the content type using Drupal 7's manage display configuration.

Jan 24 2012
Jan 24

One of the things I'll miss about Louisville, KY when I move my family to Greenville, SC next month is the buying club we're a part of that sources raw / organic foods and other products from local farms and other good companies. It was put together by a genius I knew through college and church (John Moody, who writes and speaks about food clubs and co-ops), and last year another college buddy (Kane Holbrook) started working with him to help manage the club and oversee deliveries and pick-ups. Among the many yummy things we get through the club are a variety of raw milk cheeses from Welsh Mountain Farms, an Amish farm in Lancaster County, Pennsylvania.

It just so happens that this farmer, yea, though he has no internet access himself, understands the advantages of selling online and asked Kane last year about starting a website to sell his cheese. Kane floated the idea by me, and it quickly became a business plan and partnership to start selling his cheese using Drupal Commerce. Not only did it help the farmer and open a door for Kane and I to do some business together, but it also finally gave me a chance to experience using Drupal Commerce as a site owner and administrator. After two years of planning and development, I finally started eating my own dog food when we launched in November.

I'll have more to write about the site in the future, as I learned a lot through it and contributed a lot of code from the project to It became the driving factor behind my development of the flat rate shipping module and UI improvements for on-site order management in Drupal Commerce 1.2. It's also the primary example I use to demonstrate multiple flat rate shipping options with conditional availability (think free shipping on orders over a certain amount) and custom discounts to products through an integration with quicksketch's Facebook OAuth module. It was my second foray into theming with Omega and turned up a few tips that I need to pass on to other theme developers with respect to Drupal Commerce components. Finally, it gave me my first experience launching a site on Acquia Dev Cloud using one of those handy coupons they give out at Drupal events.

But the primary purpose for this blog post is to highlight one specific difficulty we encountered while administering orders and the simple solution I put in place to resolve it. In Drupal Commerce, the shopping cart is simply an order in a special status that indicates it's "in progress" and therefore needs to be continually updated to reflect current product prices and availability. By default an authenticated shopping cart order (i.e. for a logged in user) may exist indefinitely until the user finally completes checkout for the order. (There's an issue to expire them through Rules if you're interested in reviewing it. )

We encountered a scenario where a customer added a product to his shopping cart the first week of December but didn't actually purchase the cheese until we sent out a special offer over the holidays for a free 8 oz. cheddar for orders placed in a certain timeframe. It was great to see the immediate effectiveness of the offer (recovered cart sales are a big deal), but because the Orders View on the back-end sorted orders in reverse order by creation timestamp, his order appeared down the page below orders that had already been shipped and marked as Completed. It's not a huge problem, because a filter on the View to only show Pending orders by default would highlight orders needing attention, but it still isn't an ideal user experience.

The thought occurred to me that for our scenario, it would be fine for the creation timestamp of an order to be reset to the current timestamp on checkout completion. As far as we're concerned, that's when an order has been "created" that we actually need to respond to. It actually existed before then, and we'll retain that data in the order's revision log, but we really want to know when the order was finally submitted through a complete checkout process. I started imagining where I would put code to do this when I realized I wouldn't do that at all... a simple Rule would do the trick!

This Rule reacts to the event "Completing the checkout process" and includes a single "Set a data value" action to update the created timestamp to the current time. Because every order save triggers a new revision, we'll have the historical creation date if we want it, but the date that matters to the customer and to administrators (i.e. the date of checkout completion) will now appear properly. If you need the same behavior, you can import the following Rule:

{ "rules_update_the_created_timestamp_to_now" : {
    "LABEL" : "Update the created timestamp to now",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "data_set" : { "data" : [ "commerce-order:created" ], "value" : "now" } }

Now, I should be used to the level of flexibility we achieved in Drupal Commerce by now, but it still tickles me to no end that it really is that simple to change even obscure aspects of your e-commerce system through the user interface. When I communicate the strengths of the project as an eCommerce framework, concrete examples like this make the approach come to life for merchants and store administrators. It's a clear case of the software conforming to your business needs instead of forcing you to work within its constraints, and I look forward to seeing how else we can trick it out to grow our little cheese business.

Sep 27 2011
Sep 27

In Drupal Commerce, a line item is any item added to an order that affects the order total. They represent products, shipping rates, certain types of discounts, and more. During sell price calculation for products and rate calculation for shipping, you actually apply discounts, fees, and tax rates as manipulations to the unit price of line items.

I've been dealing a lot with line items during a personal shipping sprint I've been on the last week and a half to help launch a client site. That work has involved a complete rewrite of Commerce Shipping in the 2.x branch to support carrier calculated rates (such as those returned by ConnectShip, UPS, FedEx, etc.). That work in turn has resulted in the release of a Physical Fields module that defines weight and dimensions fields and a Commerce Physical Product module that provides API support for determining when orders contain shippable products, the total weight of the order, and other useful things.

Once this site launches, I'll give more attention to the upgrade path for folks using Shipping 1.x to move up to Shipping 2.x. (I'll also need to rewrite the flat rate shipping method to go along with it.) To push forward integration with different carriers, we'll be holding a Shipping Sprint at DrupalCamp Atlanta, fittingly the corporate home of UPS.

During the course of my work on Commerce Physical Product, I was reminded that determining whether or not a line item represents a product isn't as straightforward as you would first think. It's nothing terribly tricky, but you can't just perform a simple check on the product type to reliably determine if a line item represents a product.

This is insufficient:

if ($line_item->type == 'product') {
// ...

The reason is Drupal Commerce allows you to have multiple product line item types, each with their own unique fields that may be exposed through the Add to Cart form. This feature lets you sell customizable products where the various customizations are stored with the product reference in the line item.

A simple use case is adding a custom price field to a donation product line item type allowing customers to tell you how much they want to donate to a specific campaign. This can all be configured through the Field UI and Rules, mitigating the need for modules like UC Variable Price. Trés cool.

Since you can have multiple product line item types, we provide a helper function that returns an array of the names of every product line item type defined on the site. Instead of the code above, you can perform an in_array() check on the type of a line item to see if it is of any of the valid product line item types:

if (in_array($line_item->type, commerce_product_line_item_types())) {
// ...

Any time you're writing code that should apply to a product line item, be sure to use this method instead of the first. Hope that helps you as you work on your Drupal Commerce contribs and custom modules. I almost forgot about this when writing Commerce Physical Product. Granted, I haven't been sleeping much recently, but if it's that easy for me to forget, I bet it's a bit unknown to the general public.

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web