user1801605
user1801605

Reputation: 441

How to filter a product collection based on product type and its attribute value?

Let's say in one category I have simple products and virtual products. Now for logged in and non-logged in customers, I want to filter the products to display under that category. I have no problem with the logged in and non-logged in condition. The problem is with the collection filter.

Let's say I have a "filesize" attribute for the virtual products. By observing the catalog_product_collection_load_before event, I want to filter so that non-logged in customers can see all simple products plus virtual products with filesize = 1,2 (it means 1MB and 2MB, multiselect attribute). And all logged-in customers can see all simple products plus virtual products with all filesize.

My collection code for non-logged in customers is like this:

$observer->getCollection()->addAttributeToSelect('filesize','type_id')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'))
    ->addAttributeToFilter('filesize', array('in' => array(1,2)));

But it doesn't work. How can I do that? Thanks in advance.

Upvotes: 1

Views: 7617

Answers (2)

Ashwin Parmar
Ashwin Parmar

Reputation: 3045

You can use like this:

$collection->addAttributeToSelect('filesize','type_id')
           ->addAttributeToFilter(array(array('attribute'=>'type_id','eq' => 'simple')))
           ->addAttributeToFilter(array(array('attribute'=>'filesize','in' => array(1,2))));

Upvotes: 2

MagePal Extensions
MagePal Extensions

Reputation: 17656

Take a look @ Mage_Catalog_Model_Resource_Product_Collection

Mage::dispatchEvent('catalog_product_collection_load_before', array('collection' => $this));

So in your observer try

$collection->addAttributeToSelect('filesize','type_id')
           ->addAttributeToFilter('type_id', array('eq' => 'simple'))
           ->addAttributeToFilter('filesize', array('in' => array(1,2)));

Upvotes: 0

Related Questions