1

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

1 Answer 1

2

The solution was to clone the product collection, clear it and remove the limit e.g

$collectionClone = clone $productCollection;
$collectionClone->clear();
$collectionClone->setPageSize(false);

I then looped over the cloned collection instead of the original collection and using the same logic as in the question I added the product id to an array rather than removing the item from the collection. I then applied another filter to the original collection where the product id's weren't in the array i.e $productCollection->addAttributeToFilter('entity_id', array('nin' => $productIds));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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