0

Hello i have main 4 product like

     product_name  attribute_name attribute_value
----------------------------------------------------------
     test1           catname        abc
     test2           catname        ccc
     test3           catname        ###
     test4           catname        bbb

when i sort product bye catname on product listing page than i will get null value product test3 first , but i need it in last. i have to igonre null attribute value.

I have try in toolbar.phtml for asc and desc but its not which i want.

Can anyone help me??

1
  • did you get the solution for this? i am also looking for this for Magento 2 Sep 17, 2020 at 5:58

1 Answer 1

0

You will need to rewrite the method Mage_Catalog_Model_Resource_Product_Collection::addAttributeToSort() and handle your attribute code separately.
Here is a similar example for showing products that have images on top of the ones that don't.
You can do a similar thing for your custom attribute.
Follow the example above, but make your new class look like this:

<?php
class Easylife_Sorting_Model_Resource_Product_Collection
    extends Mage_Catalog_Model_Resource_Product_Collection {
    public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC){
        //don't screw up the admin sorting
        if (Mage::app()->getStore()->getId() == Mage_Core_Model_App::ADMIN_STORE_ID){
            return parent::addAttributeToSort($attribute, $dir);
        }

        if ($attribute == 'catname') {
            $this->addAttributeToSelect($attribute);
            //add a 1|0 flag for products depending on:
            // - 0 - if the attribute value is null or empty
            // - 1 - if the attribute is not null
            $this->addExpressionAttributeToSelect(
                'has_catname',
                "(CASE WHEN {{catname}} = '' OR {{catname}} IS NULL THEN 0 ELSE 1 END)",
                array('catname'=>$attribute)
            );
            //sort by the flag set above 
            $this->getSelect()->order(array('has_catname DESC', 'catname '.$dir));
            return $this;
        }
        //if not sorting by catname let magento do its magic
        else {
            return parent::addAttributeToSort($attribute, $dir);
        }
    }
}

I haven't tested this but it should work...I think.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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