how to filter all products by custom dropdown attribute value in magento?

atif picture atif · Feb 23, 2012 · Viewed 9.3k times · Source

i have created a custom dropdown attribute with a name "by_item", and added some options to it like "Suite, Bridal, Jeans" etc.

<?php   // get all products
        $collection = Mage::getModel('catalog/product')->getCollection();
        $collection->addAttributeToSelect('*');

        //filter codition
        $collection->addFieldToFilter(array(
                        array('attribute'=>'by_item','eq'=>"Suite"),
                    ));

        foreach ($collection as $product) {

        var_dump($product->getData());
    }

    ?>

It gives nothing :(

but when i do this :

<?php 
    $collection = Mage::getModel('catalog/product')->getCollection();
    $collection->addAttributeToSelect('*');

    //filter codition
    //$collection->addFieldToFilter(array(
    //                array('attribute'=>'by_item','eq'=>"Suite"),
    //            ));

    foreach ($collection as $product) {
    echo $product->getName() . "<br />";


}

?>

it gives me all names of products . I have visited many articles but didn't come across any question :(

Answer

J&#252;rgen Thelen picture Jürgen Thelen · Feb 23, 2012

This doesn't work because you use the OR version (nested arrays) of addFieldToFilter().

What you want is the AND version. Try this:

$collection = Mage::getModel('catalog/product')->getCollection();
    ->addAttributeToSelect('*')
    ->addFieldToFilter('by_item', array('eq' => 'Suite'));

foreach ($collection as $product) {
    var_dump($product->debug());
}

EDIT

Overlooked that the OP was talking about a "Dropdown" attribute (not a textfield).

When using addFieldToFilter() to filter by a "Dropdown" attribute, you must use the option's value/id, but not the option's text/label.

For example, if your custom dropdown attribute has this options

id    text
12    Suite
13    Bridal
14    Jeans

and you want to filter by "Suite", you code it like this:

$collection = Mage::getModel('catalog/product')->getCollection();
    ->addAttributeToSelect('*')
    ->addFieldToFilter('by_item', array('eq' => '12'));

You could also use your option's text/label indirectly:

$collection = Mage::getModel('catalog/product')->getCollection();
    ->addAttributeToSelect('*')
    ->addFieldToFilter(
        'by_item',
        array(
            'eq' => Mage::getResourceModel('catalog/product')
                        ->getAttribute('by_item')
                        ->getSource()
                        ->getOptionId('Suite')
        )
    );