load customer cart in Magento

jonathanwiesel picture jonathanwiesel · Dec 4, 2012 · Viewed 9.1k times · Source

I'm trying to load a customer shopping cart so I can add products then save the cart.
I tried this but no luck with loading the cart:

    $customerCart = Mage::getModel('checkout/cart')->loadByCustomer($idUser);

    $customerCart->addProduct($idProduct,$quantity);
    $customerCart->save();

Answer

Joseph at SwiftOtter picture Joseph at SwiftOtter · Dec 4, 2012

It depends on what you are trying to accomplish. If you are in the admin, and needing to add an item into the cart (even though the admin already has this functionality), you would do it differently than when you are on the frontend. One key point that is a little confusing in Magento is that a cart is not really what stores the items - the quote does. The cart is a wrapper for the quote. If you think about it a little, it really makes sense.

So, to access a customer's quote from the admin, you do it like this:

$quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
$quote->addProduct($product, $qty);

$quote->collectTotals()->save();

If you want to access the customer's quote from the frontend, you would do it like this:

$quote = Mage::getSingleton('checkout/session');
$quote->addProduct($product, $qty);

$quote->collectTotals()->save();