Reputation: 729
I need to add custom attribute to filter for product collection
I tried below code but filter is not working
$_productCollections=$this->getLoadedProductCollection();
$_productCollection = $_productCollections->addAttributeToFilter('weight', array('lt' => 100));
below code is working
$collection = Mage::getModel('catalog/product')->getCollection();
$_productCollection = $collection->addAttributeToFilter('weight', array('lt' => 100));
I need proper way to add filter range for weight attribute like
->addAttributeToFilter('weight', array('lt' => 100));
in default product collection($this->getLoadedProductCollection();
)
Upvotes: 1
Views: 17429
Reputation: 729
I have one solution for this question
Step1:
Duplicate block code for list
\app\code\core\Mage\Catalog\Block\Product\List.php to
\app\code\local\Mage\Catalog\Block\Product\List.php
Step2:
Change below code from
$this->_productCollection = $layer->getProductCollection();
to
$this->_productCollection = $layer->getProductCollection()->addAttributeToFilter('weight', array('lt' => 100));
This is one simple solution to resolve your issue properly.
Upvotes: 3
Reputation: 171
Maybe, collection is already loaded. Add filter before loading collection
($this->_getProductCollection()->load())
Upvotes: 1
Reputation: 2123
Try explicitly selecting the attribute with:
$_productCollection->addAttributeToSelect('weight');
And then the filtering:
$_productCollections->addAttributeToFilter('weight', array('lt' => 100));
Another way is selecting by default the attribute in the product collection, by placing this in the config.xml of your module:
<config>
<frontend>
<product>
<collection>
<attributes>
<weight />
</attributes>
</collection>
</product>
</frontend>
Then you should be able to do the filter as usual:
$_productCollections->addAttributeToFilter('weight', array('lt' => 100));
Upvotes: 2