Remove items from a collection

Sometimes you need to remove items from a collection (products f.e.) after it was loaded. The following example shows how I removed non salable product items from a collection of sibling products. The respective collection have to be inherited from Varien_Data_Collection.

<?php
    public function getSiblingsCollection()
    {
        $oCollection = Mage::getModel('catalog/product')->getCollection()
            ->addFieldToFilter('sheldon_articlenbr', array('eq' => $this->getProduct()->getData('sheldon_articlenbr')))
            ->addFieldToFilter('type_id', array('eq' => Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE))
            ->addFieldToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
            ->addFieldToFilter('sheldon_color', array('neq' => ''))
            ->addAttributeToSelect('sheldon_is_sale_product')
            ->addAttributeToSelect('sheldon_is_new_product')
            ->addAttributeToSelect('sheldon_color_image')
            ->addAttributeToFilter('price', array( 'gt' => 0.0000) );


        foreach($oCollection as $sKey => $oProduct){
            if(!$oProduct->isSaleable()){
                $oCollection->removeItemByKey($oProduct->getId());
            }
        }

        return $oCollection;
    }

 

Leave a Reply

Your email address will not be published.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.