Magento – How to get available quantity of product

addtocartmagento-1.9

I am adding products in cart programmatically. But whenever I enter quantity more than available, it gives me a 503 error. e.g. Lets say a product has 7 quantity saved in admin and out of 7, 3 is already added into cart. So now 4 quantity is available.
But if I try to add more than 4 it gives me 503 error.

Now I want to add a check for quantity before adding into the cart. Is it possible?

I am using below code to add product into cart.

$_product = Mage::getModel('catalog/product')->load(1);
        $cart = Mage::getModel('checkout/cart');
        $cart->init();
        $cart->addProduct($_product, array('qty' => 5);
        $cart->save();
        Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Best Answer

You are approaching your problem from the wrong angle.

I guess you are seeing a 500 error because of an uncaught exception. The quote and cart models throw exceptions if the product cannot be added to the cart.

Use try ... catch to catch this exception and react accordingly.

Example:

try {
    $cart->addProduct($_product, array('qty' => 5);
    $cart->save()
} catch (Mage_Core_Exception $e) {
    Mage::getSingleton('checkout/session')->addException($e, $this->__('Cannot add the item to shopping cart.'));
}
Related Topic