Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :(

like image 949
atif Avatar asked Jan 18 '23 09:01

atif


1 Answers

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')
        )
    );
like image 56
Jürgen Thelen Avatar answered Jan 29 '23 06:01

Jürgen Thelen