Programatically add bundle product to cart in Magento
Sometimes, clients requirements exceed the defaults built into the Magento. Recently we came across a task that among other things required manipulation of bundle products in Magento. In order to help my coworker Tomas I wrote this little code snippet that programatically adds bundle product to cart.
$params = array(
'product' => 164,
'related_product' => null,
'bundle_option' => array(
21 => 58,
20 => 55,
11 => 28,
12 => array(
0 => 31,
),
13 => array(
0 => 32,
1 => 35,
),
),
'options' => array(
3 => 'olaaaaaaaa',
),
'qty' => 2,
);
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load(164);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$message = $this->__('Custom message: %s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
The above source code might need a bit explanation. There are two major things to keep an eye on bundle product view page, custom options and bundle items.
Custom options are set in the array
'options' => array(
3 => 'olaaaaaaaa',
),
And bundle item options are set in array
'bundle_option' => array(
21 => 58,
20 => 55,
11 => 28,
12 => array(
0 => 31,
),
13 => array(
0 => 32,
1 => 35,
),
),
Check out the screenshot for additional info.
In summary “all” you need to do is to send the proper field name-values as a params. You can then use this code from within controller or as a fast fix from within view file.