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();
}
}