Magento – How to add quantity dropdown in cart for configurable product

cartcheckoutconfigurable-productmagento-1.7

Hello
I am using magento 1.7.0.2 CE. I need to display a dropdown for product quantity to allow a user to select quantity from the dropdown on cart page. I have added a code in checkout/cart/item/default.phtml for the same which is,

<?php echo $min_sale_qty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct())->getData('min_sale_qty');
 $total_qyt = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($this->getProduct())->getQty();
     ?>
    <select name="cart[<?php echo $_item->getId() ?>][qty]">
    <?php for($i = $min_sale_qty; $i <= $total_qyt; $i = $i + $min_sale_qty)
      {
      ?>
    <option value="<?php echo $i?>" <?php echo ($i == $this->getQty())? "selected=selected": ""; ?>>
      <?php echo $i?>
    </option>
   <?php }?> 
   </select>

This code displays the dropdown correctly for simple products. But when I add configurable product to my cart, It displays me dropdown without any option to select.
Can anyone help me with it? Thanks in Advance.

Best Answer

This happens because the configurable product does not have minimum sale qty and a total qty.
You need to get the simple product that is represented by the configurable product and get the values from it. Try this:

$simpleProduct = null;
foreach ($_item->getQuote()->getAllItems() as $simpleItem){
   if ($simpleItem->getParentId() == $_item->getId()){
       $simpleProduct = $simpleItem->getProduct();
       break;
   }
}
if ($simpleProduct){
   //work your magic with $simpleProduct
}

I didn't test, but it seams like the way to go.
I've tested and this works for me. I was close. Instead of getParentId() it should be getParentItemId(). Here is the code from my checkout/cart/item/default.phtml file:

$simpleProduct = $this->getProduct();
if ($this->getProduct()->getTypeId() == 'configurable') {
    foreach ($_item->getQuote()->getAllItems() as $simpleItem){
        if ($simpleItem->getParentItemId() == $_item->getId()){
            $simpleProduct = $simpleItem->getProduct();
            break;
        }
    }
}
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleProduct);
$min_sale_qty = (int)$stockItem->getData('min_sale_qty');
$total_qyt = (int)$stockItem->getQty();

?>
<select name="cart[<?php echo $_item->getId() ?>][qty]">
    <?php for($i = $min_sale_qty; $i <= $total_qyt; $i = $i + $min_sale_qty) : ?>
        <option value="<?php echo $i?>" <?php echo ($i == $this->getQty())? "selected=selected": ""; ?>>
            <?php echo $i?>
        </option>
    <?php endfor;?>
</select>

I'm almost sure that there is an other way of getting the simple product and avoid the foreach loop but this will do for now.

Related Topic