Showing posts with label magento product collection. Show all posts
Showing posts with label magento product collection. 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.

December 17, 2014

Magento Product Collection by Attribute Filter

Add attribute to filter in product collection


The below part code shows the product collection filter by attribute.

For example
You want to filter the product collection by status enabled product,
refer the code below this do that
$collection  = Mage::getModel ('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('status',
                        array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                      );

print_r($collection);