Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add product in cart - empty cart

Tags:

php

magento

cart

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

like image 368
Camital Avatar asked Nov 01 '22 09:11

Camital


2 Answers

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.

like image 167
freento Avatar answered Nov 09 '22 16:11

freento


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());
like image 40
balrok Avatar answered Nov 09 '22 16:11

balrok