Magento Sort Attribute by Decimal not Alphanumerically

后端 未结 6 1747
刺人心
刺人心 2021-02-05 22:08

So I\'ve Googled like crazy to try and find a solution to this problem that actually works properly but have come up empty handed.

When using the Sort By function on a

6条回答
  •  猫巷女王i
    2021-02-05 22:38

    Can you tell us the 'Catalog Input Type for Store Owner'? Eg is it text or drop down? I mean, do you have a 'position' column in the Magento Admin (Catalog->Attributes->Manage attributes->Manage Label / Options->Manage Options (values of your attribute)). If your attribute is text, is the actual value the string '9kg' or is it '9' with 'kg' added later?

    Anyway, if you can set a position in the attribute editor then I think getSortOrder() will help you (confirm this and someone can post an answer about getSortOrder()).

    If you cannot set a position (because the values are not pre-determined) then I think you will need to create the product sort order yourself* by perhaps stripping out the letters from the attribute values with a preg_replace() or str_replace(), sorting on the result of that and then passing the new sorted product array into the display loop - see 'rough pseudo code' in this answer.

    *because I don't think any built-in generic sorting functions can tell the string '9kg' is less than teh string '11kg' or '3V' is less than '18V'

    **EDIT following comment:

    Ah, yes, and I see Magento does not have a numeric input type for Catalog Input Type for Store Owner. I think you should code your own sorting in the .phtml or the associated block php class (or if you know the weights in advance make it a dropdown eg 1,2,3,4... or 1.1, 1.2, 1.3...4.1, 4.2, 4.3...19.9) then you can tell Magento the position.

    You might get away with the Date input type or even the Fixed product tax input type but I reckon that is asking for trouble (and a lot of testing).

    Plan B might be to add some XML that defines a new numeric input type for Catalog Input Type for Store Owner but I'd leave that to the core Magento developers - maybe they have a good reason for storing attribute values as strings.

    If you are using the system attribute Weight then that is fixed as input type text and I think you have no choice other than coding your own sort.

    I just found

    //file: app/code/core/Mage/Core/Model/Locale.php
    //class: Mage_Core_Model_Locale
    //...
         /*
         * @param string|float|int $value
         * @return float|null
         */
        public function getNumber($value){
    //...
    

    Which could be useful. I don't think it will take you long to code your own sort.

提交回复
热议问题