Showing posts with label magento product collection filter. Show all posts
Showing posts with label magento product collection filter. Show all posts

December 19, 2014

Magento Product Collection Filter by Dropdown Option Value

Filter product collection by option value.


Filter by option value


The product collection filter by attribute option value.

$statusEnable = Mage_Catalog_Model_Product_Status::STATUS_ENABLED;
$collection  = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('status',
                        array('eq' => $statusEnable)
                      )                    
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('[attibute_name]', 
                        array('eq' => '[value]')
                      );
    

Filter by dropdown option value


The product collection filter by dropdown option value.

$sAttributeName = '[custom_attribute_identifier_id]'; //for example: color, size

/*
 * Get custom attribute option values
 *
 */
$optionValues = Mage::getResourceModel('catalog/product')
                ->getAttribute($sAttributeName)
                ->getSource()
                ->getAllOptions(false);

/*
 * Select the option id for the choosen dropdown option value
 *
 */
foreach($optionValues as $options) {

    if($options['label'] == '[choosen_value]') {
        $optionIds[] = $options['value'];         
    }
}

/* print_r($optionIds); */

/*
 * Filter product collection by dropdown option id
 *
 */
$collection  = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('status',
                        array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                      )                    
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter($sAttributeName, 
                        array('in' => $optionIds)
                      );
[choosen_value] In frontend, selected dropdown value to match option values to get option id.