In Category list view I want to create a custom collection where some products are not shown OR the entire collection is re-sorted. To test this I created an observer for the event catalog_block_product_list_collection and modified the collection removing all simple products with the following code :
/**
* Execute observer
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(
\Magento\Framework\Event\Observer $observer
) {
$productCollection = $observer->getEvent()->getCollection();
if ($productCollection instanceof \Magento\Framework\Data\Collection) {
foreach ($productCollection as $k => $product){
if ($product->getTypeId()==='simple')
{
$productCollection->removeItemByKey($k);
}
}
}
}
The collection is modified but the original collection size is not updated resulting in the frontend pagination showing 24 products, but listing only 10.
When I try and sort this collection at this point either via the observer or directly in the core code only the first page of the collection is sorted and not the entire collection.
It seems that the collection being passed to the observer is just the paginated collection for the frontend list. I need to modify the entire product collection as it is made, either by removing products or re-sorting the collection.
How can I correctly remove products or re-sort the entire product list collection so that the modified collection properties are correct i.e. collection size, and displayed normally with the correct pagination in the frontend?
$productCollection->addFieldToFilter('type_id', array('neq' => 'simple'));
?