1

How add to cart in magento works ?

As is it based on the session

OR

We can add the product to cart to a particular user using external php call



 require_once '../app/Mage.php'; 
    Mage::getSingleton('core/session', array('name' => 'frontend')); 
    umask(0);  
    Mage::app();  
    $session = Mage::getSingleton('customer/session');  
    $product = Mage::getModel('catalog/product')->load(99);  // Random product ID

    // get cart and add product
    $cart = Mage::getSingleton('checkout/cart'); 
    $cart->init();
    $cart->addProduct($product, 1);

    // update session
    $session->setCartWasUpdated(true);

    // save the cart
    $cart->save(); 

As the above code not using any session and customer id am in a bit of confusion , and i called this externally . i asked this question because i first call this via poster , and when i logged in to the site the product is not there in cart for thatuser .

3

If you need to work on the most recent active cart of a specific customer I suggest you to use the Mage_Sales_Model_Quote::loadByCustomer() method.

Here is a sample code which assumes you are in a fully initialized Magento frontend application:

/** @var Mage_Customer_Model_Customer $customer */
$customer = Mage::getModel('customer/customer')->load(<customer_id>);

/** @var Mage_Sales_Model_Quote $quote */
$quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
if (!$quote->getId()) {
    $quote
        ->setStore(Mage::app()->getStore())
        ->setCustomer($customer)
        ->save();
}
/** @var Mage_Catalog_Model_Product $product */
$product = Mage::getModel('catalog/product')->load(<saleable_product_id>);

/** @var Mage_Sales_Model_Quote_Item $quoteItem */
$quoteItem = $quote->addProduct($product, /* qty = */ 1)->save();

$quote->save();

Hope it helps.

4
  • can you give a sample of how to use it – KTM Apr 16 '15 at 10:50
  • and this is retrieval right , but how to set cart for a customer , – KTM Apr 16 '15 at 10:56
  • When i used it like :- $cart = Mage::getModel('sales/quote')->loadByCustomer($userId); print_r($cart);exit(); it wont print any – KTM Apr 16 '15 at 11:20
  • I edited my answer and added sample code; hope it helps. – Alessandro Ronchi Apr 16 '15 at 12:42
2

When you call the script it uses a Magento user session based on a cookie frontend to add the product to a particular cart tied to a session.

Since the script is probably called by a server or something like that it's not linked to your browsers session. In case this script works as it should calling it via your browser should add it to a cart that links to your browsers Magento session

0

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.