Sorting of products in Drupal Commerce Add To Cart form Sorting of products in Drupal Commerce Add To Cart form

Posted by mradcliffe on 2014.06.11 @ 13:49

Filed under:

This is a quick post regarding the sort order of option elements in the Drupal Commerce Add to Cart form as part of Product Reference fields.

I was confused as to how this was sorting. It does not sort by the Product title. It does not sort by the Product entity identifier. On my development site, the options seemed to be sorting by SKU.

There were a couple options to look into:

1. hook_form_alter().

I initially decided to give up and go the custom code route disparagingly. Although this option did in fact allow me to change the sort order to an arbitrary one, the Add to Cart form had already loaded the Product price of the default value meaning that the wrong price was displayed for the Product on initial page load.

In order to change that I’d have to write even more custom code.

Not good…

2. Change the SKU.

I found that the list was sorted by SKU. However this was not an option because changing SKUs will mess with history. And though I tried this option, it did not change the sort order. This might have worked given the actual issue below.

Not good…

The actual issue

The product list is stored as part of a Product Reference field, which can be a multi-value field. The product ids are ordered by field “delta” or in other words the ordinal in which they were stored.

The Select List field widget (and Checklist field widget) stores multi-value field items in the order of the options. So if initially the Select List grabbed the order by SKU, then that’s the storage order.

Commerce also provides an Autocomplete field widget. Field items are assigned their delta left-to-right. The Autocomplete field widget would allow sort ordering of Commerce Products.

If Product Reference field were an Entity Reference field, then select lists could pull an ordered list from a view or sort by a particular entity property or field.

Note that in the absence of any alternative (Commerce predates most of what we now enjoy in D7 : ), delta 0 was used as a dependable default. However, we have a hook as well, hook_commerce_product_reference_default_delta_alter() (documented in commerce_product_reference.api.php) that lets you specify an alternate delta value as the “default” product from a product reference mult-value field value.

Hope that helps! Commerce can be a mouthful at times. : P