1

Case:

Suppose we are observing event: catalog_product _collection_ load_before in some custom page. For example:

class MagePsycho_Custom_Model_Observer
{
    public function catalogProductCollectionLoadBefore(Varien_Event_Observer $observer)
    {
        if (Mage::app()->getFrontController()->getAction()->getFullActionName() == 'some_custom_route')
        {
            $collection = $observer->getCollection();
            $collection->addAttributeToFilter('custom_attribute', 123);
        }
    }
}

And lets say we have some other blocks which also uses the product collection to display the products, which now becomes empty as the above filter gets added.

How would you safely observe the event in this kind of situation so that it works for both(custom page & blocks)? Please share your views.

1
if  ($observer->getBlock() instanceof Mage_Catalog_Block_Product_.....) {
    // code of your observer
}
  • Sorry for the confusion. The event: catalog_product_collection_load_before is only observed once. – MagePsycho Jun 1 '15 at 19:12
  • I've edited my post, sry didn't understand your question – zhartaunik Jun 1 '15 at 19:24
  • I was thinking the same but didn't find any block reference in that observer object after inspecting via x-debug. Are you able to get some value for $observer->getBlock() ? – MagePsycho Jun 1 '15 at 19:30
  • It depends on what do you send to observer object. Shom me please the code where does your observer call. I meaned where Mage::dispatchEvent... params – zhartaunik Jun 1 '15 at 19:47
  • catalog_product_collection_load_before is the event which is observed. – MagePsycho Jun 1 '15 at 20:06
1

I would clone the original collection before applying additional filters on it. That way you can always show products from original collection and display block with filtered products.

But in your case, you are using event catalog_product_collection_load_before so you don't have any chance to clone the unfiltered collection. Maybe you will have to load the collection again to show all the products.

1

I don't think you can, using the given event.

The event observed implies that this would be the collection, as used globally, for any/all block output during the request.

If you need to target one specific block, you would need to listen to another event, more specific to that blocks rendering, and in that event, adjust the collection for that blocks usage. Another approach, if the block has its own custom class, is to place a method in the custom class which will adjust the collection at the time of rendering.

Not in front of a pc right now, so cannot give specifics, but both answers from @zhartaunik and @Kalpesh would then potentially apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.