3

Trying to find a solution for the order of the attributes in layered navigation on the category list page.

Now I have to sort them in the attributes from backend, and it is not a good way with many entries.

How can I change the dropdown for the attributes to be sorted in 1-9 and a-z ? (not from backend)

Now it can be

B
P
8
A

When it should be

8
A
B
P

Thank you !

2

I will not give you the final solution but I will direct you to a place where you change the default behaviour.

So, if the attribute does not have a custom source it uses default source class which is \Magento\Eav\Model\Entity\Attribute\Source\Table. All of the attribute options are returned in a function getAllOptions($withEmpty, $defaultValues). If you check it, you will find that in this function an attributeOptionCollection is created on which a function setPositionOrder($dir, $sortAlpha) is called. In this function we have hardcoded sort order of the options collection - $this->setOrder('main_table.sort_order', $dir);

I can give you quick 2 options to make it work as you want it:

  • make a before plugin on \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::setPositionOrder and change the $sortAlpha variable to true - I am not sure how the sorting will behave, but it should be alphabeticaly
  • make and around/after plugin on \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::setPositionOrder and change the sorting the way you want

There are of course more options, you can also make plugins for \Magento\Eav\Model\Entity\Attribute\Source\Table::getAllOptions as well as you can override it (which I do not reccomend). Let me know which option you selected and good luck!

6
  • Thank you, $sortAlpha variable to true did the trick. I might need to go deeper with the getAllOptions when I have added all the attributes. Thank you.
    – M2Newbie
    Oct 22 '18 at 9:20
  • Great. Please be aware that this modification will probably sort the attribute options alphabeticaly everywhere on the site, if this is not a problem for you thank ok.
    – Sebastian
    Oct 22 '18 at 10:07
  • I tried the above. I have used before plugin. But not working. How can I return the value.
    – Vindhuja
    Mar 20 '19 at 11:21
  • it's code not working it please help me how to specific attribute option filter by alphabetically
    – Rv Singh
    May 28 '19 at 8:52
  • Which one is not working? Have you tried making plugins on getAllOptions()?
    – Sebastian
    May 29 '19 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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