paolo@bimodesign.com | +34 608 61 64 10

E-Commerce

        

Magento, how to count the stock for the configurable products

Magento allows to manage and to define three product types, using these two lines

$product =  Mage::getModel('catalog/product')->load($product_id);
$typeId  = $product->getTypeId();

you'll get, one of:
- virtual
- configurable
- simple
- and more...

The Configurable Products let your customers select the variant they desire by choosing options.
If in case of simple and virtual, the stock is a simple parameter, in case of configurable products, this computation is quite different. A configurable product is associated a simple product data and in this oficial link you could find how configure it into the panel.
In this post I'll explain how to compute the total of the simple product and of any configurable, in order to show this information when the user change the option of choice.
The file that I modified is
app/design/frontend/default/default/template/aw_avail/stockinfo.phtml and I'm explaing the code that I added.

First of all, I get the information of the product

    $_product = $this->getProduct();
    $_helper = $this->helper('catalog/output');
    $_thumbSize   = Mage::getStoreConfig('amconf/size/thumb');
    $_previewSize = Mage::getStoreConfig('amconf/size/preview');

then I check if is a configurable or is the simple product that it's associated. In this last case, I have to show the stock too, so I compute it in this simple way

 $Inventory = Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct()->getId())->getQty();

If is configurable, I iterate through it like we normally would any product data, where the array of is came from this statment

$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();

and then I get any quantity by the getId() method.
This is the part of all the code to compute the stock (and the price).

    
    if ($this->getProduct()->getData('type_id') == "configurable") {
        $product = Mage::getModel("catalog/product");
        $prod = $product->load($this->getProduct()->getId());
        $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($prod);
        $col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();

        $Precio = $product->getFinalPrice();

        $total_qty = 0;
        foreach ($col as $sprod) {
           Mage::log('GetId '.$sprod->getId(), null, 'paolo.log', true);

           $sprod = $product->load($sprod->getId());
           $qty = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($sprod)->getQty());

           Mage::log('Quantity '.$qty, null, 'paolo.log', true);
           $Inventory+=$qty;
        }

    } else {
         $Inventory = Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct()->getId())->getQty();
    }