1
votes

I'm displaying products that have a 'selected' attribute as 'Yes' on top of my homepage.

Thus far I tried:

$_productCollection = Mage::getModel('catalog/product') -> getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('selected',array('eq'=>'Yes'))
    ->setVisibility(array(2,3,4))
    ->setOrder('created_at', 'desc')
    ->setPage(1, 48);

And:

$_productCollection = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('selected',array('eq'=>'Yes'))
    ->setVisibility(array(2,3,4))
    ->setOrder('created_at', 'desc')
    ->setPage(1, 48);

Yet as you can see, "There are no products matching the selection." But there are several products I've set the 'selected' attribute to 'Yes'.

Screenshot of my attribute: http://postimg.org/gallery/53wrrrhe/

However when I get rid of this line:

->addAttributeToFilter('selected',array('eq'=>'Yes'))

From them, they are both working fine and giving all the products as expected.

My take is I'm writing this addAttributeToFilter wrong but I'm not sure how. Any help would be appreciated!

Thanks!

1

1 Answers

4
votes

Soooooo.... since your attribute is a dropdown, you can't do the addAttributeToFilter with the eq = "Yes". The value of the attribute "selected" is the numeric value of its option stored in the database. Which could be any number.

What you have to do is this...

Figure out which option is the "yes" option.

$option_id = 0;
$options = Mage::getModel("eav/entity_attribute_option")
  ->getCollection()
  ->setStoreFilter()
  ->join("attribute", "attribute.attribute_id = main_table.attribute_id", "attribute_code")
  ->addFieldToFilter("attribute_code", array("eq" => "selected"));

foreach ($options as $option)
  if ($option->getValue() == "Yes")
    $option_id = $option->getOptionId();

Then you can do what you did above with "eq" => $option_id.

$_productCollection = Mage::getModel('catalog/product') -> getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('selected',array('eq'=> $option_id))
    ->setVisibility(array(2,3,4))
    ->setOrder('created_at', 'desc')
    ->setPage(1, 48);

Perhaps there is a cleaner way to do this - but this is what I've done.