Magento – How to set is_in_stock to 0 for configurable product when all associated products are out of stock

magento-1

I am using a third party service to generate and submit the product feed to Google.This service uses is_in_stock field from the cataloginventory_stock_item database table to check if the product is in stock or not?

I have check in the default Magento even if we make all the associated products of a configurable product out of stock the is_in_stock value is set to 1 only.

Or do we have any other attribute in any of Magento table which may help?
Is there any way to work around this thing.

Best Answer

Hi you can do this using magento event and observe and on create an event on catalog_product_save_after and check on obsever child product are out stock an set configurable accoring to ite

<global>
            <events>
            <catalog_product_save_after>
                <observers>
                    <stockalert>
                        <type>singleton</type>
                        <class>check/observer</class>
                        <method>autoupdatemy</method>
                    </stockalert>
                </observers>
            </catalog_product_save_after>
        </events>
</global>

and observer.php

 public function autoupdatemy($observer)
{
    try{
        $isstcok=false;
        if($observer->getEvent()->getProduct()->getData('type_id')=='configurable'){
        $ConfiProduct=$observer->getEvent()->getProduct();
        $allProducts = $ConfiProduct->getTypeInstance(true)
        ->getUsedProducts(null, $ConfiProduct);

            foreach ($allProducts as $product) {
                /* check one child product is out of stock */
            if($product->getIsInStock()==1):
            $isstcok=true;
            endif;
            }

        /* load configuale product  stock object */ 
        $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($ConfiProduct);
        if($isstcok=true):
            $stockItem->setData('is_in_stock', 1);
        else:
            $stockItem->setData('is_in_stock', 0);
        endif;
        $stockItem->save();
        }
    }catch(Excpetion $e){
    Mage::log(print_r($e->getMessage(),1),'null','mage32173.log');
    }
    return;
}