0

In a bit of a pickle trying to get multiple products to add to cart, effectively I have a block with a form element that defines the products that are added to the cart (free products, which is handled with an observer event). The observer event to change the products price to free is working fine however, adding more than one product to the cart is proving troublesome with the following method:

public function addFreeItems($observer) {
$cart = Mage::getSingleton('checkout/cart');
$freeItems = $_SESSION['package_free_item'];
$freeItemSplit = explode(",", $freeItems);
try {
    foreach ($freeItemSplit as $product) {
        $product = Mage::getModel('catalog/product')->load($product);
        $cart->addProduct($product, array('qty' => '1'));
        $cart->save();
    }
} catch(Exception $e) {
       Mage::log($e->getMessage());
       echo $e->getMessage();
    }
} 

The method works for a single item and adds fine, however the subsequent item (which is definately defined in the array at position [1]) doesn't add to the cart.

I'm at a loss as to why this doesnt work as technically it should. No exceptions are being caught in the adding process, and debugging also shows the array as populated with two items.

Can anyone give any light as to why this isn't working?

Thanks!

XML Update:

<sales_quote_add_item>
        <observers>
            <priceupdate_observer>
                <type>singleton</type>
                <class>Edge_Package_Model_ObserverPrice</class>
                <method>updatePrice</method>
            </priceupdate_observer>
        </observers>
</sales_quote_add_item>

Effectively it updates the pricing of a package, but also calling the add free products from within it.

EDIT 2:

public function addFreeItems($observer) {
$route = Mage::app()->getFrontController()->getRequest()->getRouteName();
if($route == "packages" && $_SESSION['package_free_item'] != null ) {
    $freeItems = $_SESSION['package_free_item'];
    $product_ids = explode(",", $freeItems);
    $cart = Mage::getSingleton('checkout/cart');
        foreach ($product_ids as $product_id) {
        $product = Mage::getModel('catalog/product')->load($product_id);
        $cart->addProduct($product, array('qty' => '1', 'product_id' => $product->getId()));  
        }
    $cart->save();
    }
}
evensis
  • 172
  • 3
  • 15
  • Moving the $cart->save() method outside of the cart has allowed the additional item to be added to the cart, however, the first item has been added twice!! Quantity is defined, why this is happening i'm yet to work out. – evensis Dec 04 '12 at 11:08

3 Answers3

0
<checkout_cart_product_add_after>
        <observers>
            <priceupdate_observer>
                <type>singleton</type>
                <class>Edge_Package_Model_ObserverPrice</class>
                <method>updatePrice</method>
            </priceupdate_observer>
        </observers>
</checkout_cart_product_add_after>

public function addFreeItems($observer) {
   $quote = Mage::getSingleton('checkout/session')->getQuote();
   //foreach loop
   $quote->addProduct($product, array('qty' => '1', 'product_id' => $product->getId()));
}

see method addProduct in /app/code/core/Mage/Checkout/Model/Cart.php

See http://magentocommerce.com/boards/viewthread/39334

MagePal Extensions
  • 17,646
  • 2
  • 47
  • 62
  • Thanks R.S, unfortunately not working, I had read that question as to why I have to product model reiterating inside the loop. Same issue persists :-/ Tried saving the cart inside the loop, however, different issue where only 1 product shows up. – evensis Dec 04 '12 at 11:49
  • Does any of your product have options? – MagePal Extensions Dec 04 '12 at 12:15
  • None - Both products are simples. – evensis Dec 04 '12 at 12:23
  • Interestingly running - $quote_item->getQty(); shows: 2012-12-04T12:23:57+00:00 DEBUG (7): Second product is correctly outputting 2012-12-04T12:23:57+00:00 DEBUG (7): 1 So as far as Magento is concerned the first product (the quantity of 2 offender) has no quantity set to it in the cart... Setting quantity via $quote_item->setQty(1); sets the quantity to 3?!?!?! – evensis Dec 04 '12 at 12:25
  • Take a look at my updated code, I tested in on v1.7 and it does work – MagePal Extensions Dec 04 '12 at 12:30
  • It does indeed, interestingly enough not in an observer however. Wonder whats going on. – evensis Dec 04 '12 at 12:37
  • What observer are you using, let me see the code (xml). sometimes doing saving in observer causes issue – MagePal Extensions Dec 04 '12 at 12:49
  • Updated question with the xml! – evensis Dec 04 '12 at 12:56
  • Please remember to accept my question if it work or make edit as need... An next time dont wait until hours later to mention that you are using a observer – MagePal Extensions Dec 04 '12 at 13:23
  • Chucking me requested quantity is not available errors at the moment so not quite, did mention about the observer in the first paragraph! – evensis Dec 04 '12 at 13:28
  • That is the question, it's trying to add the defined product id via the checkout_cart_product_add_after observer but seem to be trying to add an unimaginable amount to the checkout, just enabled backorders to try and get around it and the php script is just sat executing, eek! – evensis Dec 04 '12 at 13:37
  • It may help if you understand the workflow: http://development.mytuxedo.co.uk/index.php/packages/mens/platinum/ – evensis Dec 04 '12 at 13:42
  • $cart->save(); was the offender. Got it working with $cart->addProductsByIds($product_ids); not the most ideal method, but does the trick and don't believe we need multiple free quantities added to the cart! – evensis Dec 04 '12 at 14:04
  • Is it working now? If you look at my previous post 1+ hr ago.. i told you doing saving in observer will sometime cause unknowing issues – MagePal Extensions Dec 04 '12 at 14:15
  • Is working, certainly observer's will wreak havoc with working code! Your code doesn't work however in the observer function, needs the addProductsByIds() method for it to work. – evensis Dec 04 '12 at 15:32
0

I've run into this as well and you need to declare

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

inside the foreach. I'm not sure why it works, but it does seem to work for me.

Ryan
  • 729
  • 2
  • 13
  • 26
0

May be this one will help:

http://deepakbhatta.com/magento-add-multiple-items-to-cart/

 $cart = Mage::helper('checkout/cart')->getCart();
        $ms="";
        foreach($validProducts as $sku => $qty) {
            $params = array('qty' => $qty);
            $id = Mage::getModel('catalog/product')->getIdBySku($sku);
            $product = Mage::getModel('catalog/product')->load($id);;
            $cart->addProduct($product, $params);
            $msg .= $product->getName(). " is successfully added into cart<br>";
        }
         $cart->save();
Deepak Bhatta
  • 474
  • 4
  • 16