Snippet: How to modify text of add-to-cart product select (multiple products in display)

Say we are selling rugs, and there is a style "Dots" in 3x6, 4x5 and 2x8, and also colors Red, Blue and Green. That's a lot of rug Products, but thankfully we can group them in one "Dots" product display.

However we named each rug descriptively (or maybe bulk content creation did it for us) like so: Dots Rug Red [3 x 5], On the product type we have a textfield for the color and a term reference for the size.

Now we have a problem: in the Product display our way of switching between the kinds of Dots is a menu named "Select a Product" and the text is the Product title. We would much rather have the select be labeled Color: and the options Red/Green/Blue.

I looked high and low for the solution for this and having figured it out for myself I post the solution here.

The answer is to use a custom module and hook_form_alter; specifically the flavor provided specifically for the Commerce add to cart forn.

in our custom module named mm_utils we have:

* Implements hook_form_FORMID_alter()
function mm_utils_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $line_item = $form_state['line_item'];
  $pid = $line_item->commerce_product[LANGUAGE_NONE][0]['product_id'];
  $product = commerce_product_load($pid);
  if(is_array($form['attributes']['product_select']['#options']) && !empty($form['attributes']['product_select']['#options'])) {
  $form['attributes']['product_select']['#title'] = "Color:";
   foreach($form['attributes']['product_select']['#options'] as $key => $value) {   
  if ($key != $pid) $product = commerce_product_load($key);
  $newSelectLabel = $product->field_color['und'][0]['safe_value']; // set the select to the color of the product
      $form['attributes']['product_select']['#options'][$key] = $newSelectLabel;

This presumes that all your products have a field called field_color. If not, you can check the $product->type to see if its the product type you are after.

The final twist is that your utility module may run BEFORE commerce calls form_alter and adds the attributes to the form, so you may need to set the weight of your module to some positive number like 100 in the system table.

Posted: Jul 26, 2012


ransomweaver on July 26, 2012

Actually, there is a problem... It seems that the attributes array is not always present containing the product_select key. I have several different product types. The one I got it working for has a size attribute that the user can choose as well as the product title to switch the product. I think that if there isn't an attribute that differentiates the products, the attributes array is missing and there is no way to access the product_select to rewrite it. Does anyone know a way to force ['attributes']['product_select'] to appear?