Programmatically add product in cart - empty cart

10,002

Solution 1

Try to change

$cart = Mage::getModel('checkout/cart');

to

$cart = Mage::getSingleton('checkout/cart');

Cart is a singleton, because you have only 1 cart on your store for 1 user and all who want to use it can call it as getSingleton, without creating new object. If you use Mage::getModel('checkout/cart') it will create a new object. Ye, it will allow you to save quote to DB, but this will not be current active customer cart.

Solution 2

You need to refresh the itemcache of the Itemcollection. Because this will also remove the quote-model from it, it must be added after that too

$cart->getItems()->clear();
$cart->getItems()->setQuote($cart->getQuote());
Share:
10,002

Related videos on Youtube

Camital
Author by

Camital

Updated on June 04, 2022

Comments

  • Camital
    Camital almost 2 years

    I'm trying to add a product in cart but the cart stay empty. Here's my code

    try{
        $product_model = Mage::getSingleton('catalog/product');
    
        // Load product
        $_sku = "1-574#AD-B00731";
        $my_product_id  = $product_model->getIdBySku($_sku);
        $my_product     = $product_model->load($my_product_id);
        $qty_value = 1;
    
        // Add to cart 
        $cart = Mage::getModel('checkout/cart');
        $cart->init();
        $cart->addProduct($my_product, array('qty' => $qty_value));
        $cart->save();
        print_r($cart->getItemsQty().PHP_EOL);
        Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
        var_dump("working");
     }
    catch(Exception $e){
        return $e->getMessage();
    }
    

    When I print $cart->getItemsQty() my item quantity are incremanting but my cart is still empty. I think it's Mage::getSingleton('checkout/session')->setCartWasUpdated(true); that is not working properly.

    Anybody have an idea of what is not working?

    Edit 1: I use Magento 1.8.0, so via an url query is not working because of the form_key

  • Camital
    Camital over 10 years
    How can I get the customer's cart?
  • freento
    freento over 10 years
    Did you the to change your script as I suggested? To get current customer cart use Mage::getSingleton('checkout/cart')->getQuote(); or Mage::getSingleton('checkout/session')->getQuote();
  • Camital
    Camital over 10 years
    Yes I did and my cart is still empty
  • Camital
    Camital over 10 years
    I just overwrited the CartController and now I use the URL methode