For instance I've size attribute and I add XL before L or M it shows up in that sequence in add to cart form.
What I would love to have is it being sorted by the order set in Product Attributes so it will be S, M, L, XL and so on.
Simple code for form_alter (this is only workaround and should go into the form class itself where sorting is done. But it should be configurable.
// Sort the add to cart form attributes by it's weight.
$attribute_storage = \Drupal::entityTypeManager()->getStorage('commerce_product_attribute_value');
foreach (Element::children($form['purchased_entity']['widget']) as $widget_index) {
$widget = &$form['purchased_entity']['widget'][$widget_index];
foreach (Element::children($widget['attributes']) as $attribute_code) {
$attribute = &$widget['attributes'][$attribute_code];
if (count($attribute['#options']) <= 1) {
continue;
}
$attributes = $attribute_storage->loadMultiple(array_keys($attribute['#options']));
uksort($attribute['#options'], function ($a, $b) use ($attributes) {
return $attributes[$a]->getWeight() > $attributes[$b]->getWeight() ? 1 : -1;
});
}
Comments
Comment #2
ginovski commented+1, this should be implemented
Comment #3
abdhomsi commented+1
Comment #4
jon pollard commentedMy project really needs to be able to do this - product sizing not being in the correct order is not a great option!
It would be great to have a patch for this - or some indication of where/how to use the code that you have posted. Any help from anybody would be really, really appreciated!
:o)
Comment #5
jon pollard commentedInvestigating this further, it appears that product attributes are displayed on the add to cart form in the order that they are placed in the product variations page. So, these are set on a per product basis, rather than by a rule. That seems a bit mad to me - although it does mean I can fix products where these are not in the right order.
Comment #6
flyke commentedI had to resort to something like this:
Comment #7
jsacksick commentedhm... I get the request, however this would essentially mean that the variations order is no longer respected if we change this... Currently variations can be reordered from the product variations tab, if we change this, this would essentially make the variations ordering "useless".