2

add to cart products with max qty of products with below code

include 'app/Mage.php';
Mage::app();

Mage::getSingleton('core/session', array('name' => 'frontend'));

// Need for start the session
$cartHelper = Mage::helper('checkout/cart');
    $items = $cartHelper->getCart()->getItems();
    echo count($items);
    foreach($items as $item)
    {
        $itemId = $item->getItemId();
        $cartHelper->getCart()->removeItem($itemId)->save();
    }

try {

    $product_id = '7896'; // Replace id with your product id
    $qty = '99'; // max qty with your qty
    $product = Mage::getModel('catalog/product')->load($product_id);
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($product, array('qty' => $qty));
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

} catch (Exception $e) {
    echo $e->getMessage();
}
  • products qty available in store is 99 with products id - 7896
  • when my script first time run add 99 qty in cart ..but next time run its give error to "The requested quantity for 'xxx' is not available"

its look like run script as

1st time - working (add to cart with 99 qty)

2nd time - given error

3rd time- working (add to cart with 99 qty)

4th time - given error and

continues,,,,

I have all ready remove cart item every time before add product as you see in code ..but its not getting same response as working ..

2

Try this

$session = Mage::getSingleton('checkout/session');
$session->getQuote()->delete();
$session->clear();

$cart = Mage::getModel('checkout/cart');
$cart->setQuote($session->getQuote());

$product = Mage::getModel('catalog/product') -> load($product_id);
if ($product) {
    if ($product -> isSaleable()) {
        $cart -> addProduct($product, array('qty' => $qty));
    }
}

// $session->setCartWasUpdated(true); // Not really necessary - Vicary
$cart->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.