0

I'm building a store in D7 and Commerce 1. My product variations have a Size attribute - these are displayed in the Add to Cart block as a list of radio options.

I would like the option labels to include the price of that variation, e.g.

  • Small - $10
  • Medium - $15
  • Large - $20

These labels should be generated automatically from the price.

I figure this could be achieved with a simple function, but I haven't been able to find one. Any suggestions welcomed!

1 Answer 1

0

OK. I got it working. Perhaps not quite as simple as I'd hoped, but this function will do the trick ...

function commerce_price_attribute_form_commerce_cart_add_to_cart_form_alter(&$form, $form_state) {
    if (isset($form['attributes'])) { 
        $entity = entity_load_single($form_state['context']['entity_type'], $form_state['context']['entity_id']);
        foreach (element_children($form['attributes']) as $field) { 
            foreach (field_get_items($form_state['context']['entity_type'], $entity, 'field_product') as $product) { 
                $product = commerce_product_load($product['product_id']);
                $status = entity_metadata_wrapper('commerce_product', $product)->status->value();
                if ($status) {
                    $items = field_get_items('commerce_product', $product, $field);
                    if (is_array($items)) {
                        $attribute = reset($items);
                        $attribute = taxonomy_term_load($attribute['tid']);
                        $items = field_get_items('commerce_product', $product, 'commerce_price');
                        $item = reset($items); 
                        $price = commerce_currency_format($item['amount'], $item['currency_code'], $product); 
                        $form['attributes'][$field]['#options'][$attribute->tid] = $attribute->name . ' - ' . $price;
                    }
                }
            }
        }
    }
}

Note that the $status value checks whether the variation is disabled and skips over it if it is - without that, disabled products were still showing in the list of options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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