Tuesday, September 25, 2012

Catalog product collection sort by attribute( select type ) value position


>> By default if you set an attribute(select type) in sort by dropdown. It'll sort by the attribute option's name.
          e.g. Color => 'Black', 'Red', 'White'
     but you want show the product of this attribute like : Color => 'White', 'Black', 'Red'
     Then set the option position here :

       

      Now open this page : app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Table.php

      Find this function addValueSortToCollection at line 112.

      In this function you'll find the code:

      $collection->getSelect()
                ->order("{$this->getAttribute()->getAttributeCode()} {$dir}");


      You've to change this code for your "Color" attribute    
      Replace the above code with the following :

     <?php
      if($this->getAttribute()->getAttributeCode() != 'color'){                // Attribute Code here
              $collection->getSelect()
                ->order("{$this->getAttribute()->getAttributeCode()} {$dir}");

      }else{
             $table = Mage::getSingleton('core/resource')->getTableName('eav_attribute_option');
             $collection->getSelect()
                            ->joinLeft(array('so' => $table), 'IF('.$valueTable2.'.value_id > 0, '.$valueTable2.'.value, '.$valueTable1.'.value) = so.option_id')
                            ->order(array('so.sort_order ASC'));

     }
     ?>

Now, you'll see the product first which selected 'White' and so on..

Note :  If no color option selected for some product that show at first. So, you've set the color for all products. OR you can change the order   ->order(array('so.sort_order ASC')); To ->order(array('so.sort_order DESC')); and set the position reverse. greater value first.