Question

I am trying to add additional filters to a collection after the collection seems to of been generated. In catalogue product list.phtml there is the following line of code:

$_productCollection = $this->getLoadedProductCollection();

When I var_dump this it does report back as a collection (Mage_Catalog_Model_Resource_Product_Collection). However if I try to add:

$_productCollection->addAttributeToFilter('attr_handle', array('eq' => 155));

directly after the first line, the resulting collection is still exactly the same. How can I modify what is in $_productCollection in list.phtml?

Any help is appreciated

---- UPDATE ----

I notice that in the List.php block the collection is loaded in the _beforeToHtml method:

$this->_getProductCollection()->load();

I am assuming therefore I have to "unload" (?) it and then apply my filters in the view and then re-load it (?)

Was it helpful?

Solution

You can call $collection->clear(), apply your filters, and then reload the collection. However IIRC the collection will be in a different state than the layer model expects.

This a combination of both Mage_Catalog_Model_Resource_Product_Collection::clear() and Varien_Data_Collection::clear().

OTHER TIPS

You can filter product collection before loading. See following, your config.xml

<frontend>   
       <events>
            <catalog_product_collection_load_before>
                <observers>
                    <ssd_ajaxify>
                        <class>SSD_Ajaxify_Model_Observer</class>
                        <method>catalogProductCollectionLoadBefore</method>
                    </ssd_ajaxify>
                </observers>
            </catalog_product_collection_load_before>
        </events>
</frontend>

And Observer.php:

class SSD_Ajaxify_Model_Observer
{    
public function catalogProductCollectionLoadBefore($observer)
        {
            $request = Mage::app()->getRequest();
            $path    = implode('_', array(
                $request->getModuleName(),
                $request->getControllerName(),
                $request->getActionName(),
            ));
            if ($path == 'catalog_category_view') {
                $collection = $observer->getEvent()->getCollection();
                $collection->addAttributeToFilter('price', array('gt'=> 50));
            }
        }
}

By the way this affects to your toolbar and layered navigation, and also product list in category view page.

By using rewrite Magento Product List Block, we can add an extra filter in product collection.

Please use below link for reference:-
[http://shariqnasir.blogspot.in/2011/06/override-core-modules.html][1]
[http://pratikkhamar.wordpress.com/2012/04/13/magentooverride-block/][2]

Hope this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top