0

I am programming an extension which adds relevant products to the cart once you add an item to the cart. Example if you are buying a pen I am going to add paper to the cart. Bundled packages are not an option since I need to match certain conditions. I tried the following:

I set up an event listener "sales_quote_item_collection_products_after_load" scan all the products in cart and add the relevant products. Sadly you have to reload the cart in order to make the products appear.

I used this code in, my event listener, to add products to cart:

// Get cart instance
$cart = Mage::getSingleton('checkout/cart'); 
$cart->init();

// Add a product (simple); id:12,  qty: 3 
$cart->addProduct(12, 3);

$cart->save()

The strange thing is that removing products using the cart helper works (without refreshing):

$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
    if ($item->getProduct()->getId() == $productId) {
        $itemId = $item->getItemId();
        $cartHelper->getCart()->removeItem($itemId)->save();
        break;
    }
}

Is there a way to tell Magento to "requote" or what would you recommend? I also thought of adding the product, at the add to cart listener. But in that case I will need to implement it as well on update and remove, so it will work correctly. Using sales_quote_item_collection_products_after_load after load seemed to be the best option, since I have everything in one place.

  • Found something interesting but its doing it with the add to cart event [link](http://stackoverflow.com/questions/5104482/programmatically-add-product-to-cart-with-price-change) – NetworkSys Co. Ltd Dec 21 '14 at 21:47

1 Answers1

0

You need to change in your code

  $product_model = Mage::getModel('catalog/product');
  $product_id =35;          
  $my_product = $product_model->load($product_id);  
  $cart = Mage::getModel('checkout/cart');
  $cart->init();
  $cart->addProduct($my_product, array('qty' => 1));
  $cart->save();   
  Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 
  • you can check by put echo statement before my code echo 'text';$product_model= Mage::getModel('catalog/product');...... If echo text is printed in frontend then product must be added to cart. – Emipro Technologies Pvt. Ltd. Dec 23 '14 at 07:23