I have a category where I want to display only those configurable products, which have simple products with some specific sizes. If the configurable product does not have a simple product with the required size, it should not show up. I use the catalog_product_collection_load_after
event in order to avoid problems with the pagination and layered navigation.
The observer is working and I am able to get the option values of the attached simple products, but I am unable to remove the parent configurable products dynamically if it has no simple product with the required size - it is working if I hardcode the parentId though. This is my function:
public function getPlusSizeProducts(Varien_Event_Observer $observer)
{
$collection = $observer->getEvent()->getCollection();
$plusSizes = array('59', '128'); // Show configurable products which have simple products with these sizes/option ids
$availableSizes = array();
$parentIds = array();
if ($collection instanceof Mage_Catalog_Model_Resource_Product_Type_Configurable_Product_Collection)
{
foreach($collection->getItems() as $item)
{
$availableSizes[] = $item->getProductSize(); // Get option ids from product
if (count(array_intersect($plusSizes, $availableSizes)) == 0 )
{
$parentIds[] = $item->getParentId();
$collection->removeItemByKey($item->getParentId()) // does nothing
}
}
}
$collection->removeItemByKey($parentIds[0]) // does nothing, array is empty
}
How can I remove the configurable products using parentId?
Ideally I'd also like to use the catalog_product_collection_load_before
event to apply some filters on the collection upfront, but I always get a 500 internal server error when trying to load the collection with ->load();
I appreciate anything which points me into the right direction =)
EDIT: Based on Marius answer I modified my code, but I still can't get it to work. I am unable to get the parent ids into one single array outside the loop (even though it is defined there) - which is what I need based on my understanding. Instead the function creates a $parentIds array for every product in the collection.