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:
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.
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.
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.