After filtering a product collection and removing an item the size of the collection returned is incorrect, although the product output/count is as expected. This causes an issue on the category list page as it will display "showing items 3-5 of 6" when there are only 5.
Using the event catalog_block_product_list_collection
i'm getting the product collection like so $productCollection = $observer->getEvent()->getCollection();
I then clear it and apply a filter to it:
$productCollection->addAttributeToFilter(array(
array('attribute' => 'example_attr_1', 'finset' => $websiteFilter),
array('attribute' => 'example_attr_2', 'finset' => $websiteFilter)
));
I'm filtering for products with a matching value in either attribute, but I then have to loop over the collection to check if example_attr_2
has a value, if so it takes priority over example_attr_1
and if the $websiteFilter
value isn't in the array of values which i get from example_attr_2
then the product is removed from the collection using $productCollection->removeItemByKey($_product->getId());
After this i set the collection $observer->getEvent()->setCollection($productCollection);
I don't think it's possible to do what I need using the collection filters? so I had to loop over the collection and remove the item but this causes the problem with the collection size. I found this answer related to the collection getSize() method.
https://stackoverflow.com/a/20578447/1156764
I guess at this point the collection has already been loaded so the totalRecords has been set, any ideas?
Thanks