Programatically add bundle product to cart in Magento

Featured Image

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.

28
Top

Care to rate this post?

Author

Branko Ajzele

Ex Inchooer

Worked at Inchoo as a Backend Developer/CTO from 2008 to 2013

Other posts from this author

Discussion 28 Comments

Add Comment
  1. Sean

    This is very helpful, but I have a question. Do you first need to create all these options for the bundle product? I am looking for a way to dynamically build a bundle product where someone can choose hundreds of options for each component. Essentially, I’d like for a customer to be able to choose from the entire “DDR2 Memory” category instead of choosing preselected options.

  2. Jon

    First of all, thank you. Second, I had to do:
    $session = Mage::getSingleton(‘core/session’, array(‘name’=>’frontend’));

    in order for this to work – just wanted to post in case that may help someone in the future.

  3. Bhavesh Dave

    Thans bro..!
    its help me a lot..

  4. Mitch Viner

    Thanks for this. Just saved me, I know a good 10 hours of reading, then try / undo / try again!

    Only thing I would add is if any options are using the select or multi-select type, you’ll need to pass the id(will be integer) of those, not the value.

  5. This is a big help!

    What about “info_buyRequest” options? how would you enter those into the array?

    for example, the HTML field name isn’t prefixed with “option_”.. instead, it has a name that seems to be unique to the plugin i’m using.

    	custom date option:
    

    I’ve tried a dozen different ways to add these custom fields to the “params” array without success…

    Thanks for any insight!
    Sean

  6. Jon

    Anyone know how to do this on the backend? So I can create an order with simple products no problem, but haven’t been able to figure out how to do it with bundle products…. Any help would be greatly appreciated.

  7. landykos

    I have been trying to figure this out but was a little unsure on something. Maybe you can help me out.

    The bundle option array. Are the ids in that array suppose to be the

    selection_id => option_id

    or

    option_id => selection_id

    'bundle_option' => array(
            21 => 58,
            20 => 55,
            11 => 28,
            12 => array(
                0 => 31,
            ),
            13 => array(
                0 => 32,
                1 => 35,
            ),
    

    Also can you explain what is going on with the multidimensional array:

    12 => array(
        0 => 31,
    ),
    

    Is this how we can add qty to the options? If so what do the numbers represent?

    Any help would be great!!

    Thanks!!
    Landy

  8. One thing I just ran into on Enterprise v 1.9.0, if you do the following:

    $newProd = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sku);
    $cart->addProduct($newProd);

    The category inventory observe throws the following exception:
    Mage::throwException(Mage::helper(‘cataloginventory’)->__(‘The stock item for Product is not valid.’));

    The stock item object it gets from the product object is a basic Varien Object.

    When I do the following, it behaves nicely:
    $newProd = Mage::getModel(‘catalog/product’);
    $newProd->load($newProd->getIdBySku($sku));
    $cart->addProduct($newProd);

    Of course, I also check $newProd->isSalable() prior to adding to the cart. Not sure exactly why it’s not loading up the proper object, hopefully this helps someone else running into this!

  9. ABOVE CODE IS NOT WORKING ON CONTROLLER FILE ..WORKING FILE WITH THE VEIW.PHTML
    CAN U TELL ME WHERE AM I WRONG

  10. Charlie

    Thanks Mage Nation! That solution to “Stock item for product is not valid” worked wonders for me.

  11. Hey,
    I have read a few of your posts on bundled products and was wondering if you might know a way to add them to an order that is being created in the admin. This does not seem possible.

  12. Jon

    Hey Mike, you are correct, with Magento versions less than 1.5 you can not. Version 1.5 adds the ability to do so though.

  13. Fida

    Hello

    Is there any possibility in magento 1.5 to get the bundled product available in cart page. if so i need to show the bundled product available for that product in a pop up and the user can edit the qty from there too.

    Waiting for your suggestion!!!!!!!!!!!!!!

  14. Fida

    thanks so much for this great article. I would like to know how i can specify the qty of bundle option products, for example if i permission for user defined qty while choosing the products

    Kindly waitng for your suggestion!!!!!!!!!!!!!

  15. Milen Petrov

    Today I spent some hours breaking my head to discover how can I add items Qty. Finaly…. Yes, it is possible to add bundle items Qty. Just use this:

    $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,
            ),
        ),
        'bundle_option_qty' => array(
             21 =>2
        ),
        'options' => array(
            3 => 'olaaaaaaaa',
        ),
        'qty' => 2,
    );
    

    It will add 2 items for option_id 21.
    Hope this helps.

  16. Milen Petrov

    In addition to adding bundles programatically it is aslo possible to do it via URL – again including the bundle items Qty.
    The URL should look like:
    http://yoursite.com/checkout/cart/add/product/bundle_id/?bundle_optionX=a&bundle_option_qtyX=aa&bundle_optionY=b&bundle_option_qtyY=bb&bundle_optionZ=c&bundle_option_qtyZ=cc&qty=number_of_bundles_to_be_added

  17. Milen Petrov

    Sorry, in my previous post I used “[" and "]” for bundle_option but for some reason it was ignored.
    Let me try to put the whole URL again in a different way.

    “http://yoursite.com/checkout/cart/add/product/bundle_id/?bundle_option[X]=a&bundle_option_qty[X]=aa&bundle_option[Y]=b&bundle_option_qty[Y]=bb&bundle_option[Z]=c&bundle_option_qty[Z]=cc&qty=number_of_bundles_to_be_added”

  18. dgento

    I am trying to add one more product to cart when add to cart button is clicked. But the code mentioned here only works in template, not in controller. any idea about this not happening?

    Thanks

  19. dgento

    Just like to share the solution: rewrite cart controller.

    under addAction()

    $params1['qty'] = 1;
    $cart = Mage::getSingleton(‘checkout/cart’);
    $product1 = new Mage_Catalog_Model_Product();
    $product1->load(194);

    After this, follow magento default code.
    add following before saving $cart

    $cart->addProduct($product1, $params1);

    //This adds new product to cart along with the product that is clicked to add to cart.

  20. Gala Grant

    I am trying to add a bundle product using the URL method you gave, which is great. The problem I have is I need to have more than one selection for an option. Whatever code I have tried it only adds the last one. For example, my product they get to choose 3 different colors. How would I do this through the URL?

  21. I am trying to get the product details in onepage.php but i am failed. I have tried many codes but i am not getting it. Do i need to get it using the sessions ? anybody know the code how do i will get the product details inside the onepage.php page ?

    ok first when i click buy a product it redirect to checkout/cart/ which means cart.phtml and cart.php well in this page i have the product name price qauntity grand total. Ok after i click the Procced to checkout then it redirect to checkout/onepage/ … onepage.php and onepage.phtml

    ok now i have set a email in the onepage.php that whenever the user click in the Procced to checkout button from the cart page when the onepage.php load it will send email.

    Well now inside the email i would like to add the product details like product name quantity company name. In here i have completed all steps but can’t get the product details. The product will be the product the user select to procced checkout.

    here is my simple email template:

    $to = "$email";
        $from = "test@test.com";
        $subject = "email test";
        //begin of HTML message
        $message = <<<EOF
    <html>
      <body bgcolor="#DCEEFC">
        <center>
            <b>email test</b> <br>
            <h1><font color="red">Your Coupon Code:</font>$letters$random_chars<br></h1>
    <h1>Product Name : $productname</h1>
    <h1>Company Name : $comname</h1>
        </center>
      </body>
    </html>
    EOF;
    $headers  = "From: $from\r\n";
    $headers .= "Content-type: text/html\r\n";
    mail($to, $subject, $message, $headers);

    well so here i have send the email its working fine just need to include the product name and company name but i am not getting how i will get it ?

  22. Bikram

    Can we change the price of the bundle items while adding to cart

  23. Hi
    i follow all these steps as mention you in your post but when i try run that i am getting this error can make sure your script is running fine in magento latest version , and also tell me how can i find bundle_option id ()

    Fatal error: Call to a member function getPosition() on a non-object in D:\xampp\htdocs\chocomize\app\code\core\Mage\Bundle\Model\Product\Type.php on line 855

  24. Rased

    Hi,
    I am facing a problem and can’t figure out the things with Magento 1.7.0.2.
    I am using external code for add to cart which is working fine when I am using it as new customer or not logged in first time. But when I am logged in as return customer it’s no more adding to cart.

    The steps as follow:
    1. I am new on site and add to cart is ok.
    2. I am new or old logged on site and it’s not adding to cart not more. It’s only show what previously I have on cart. No new items are adding to cart.

    3. Now I have clear my browser cache and cookie, now it’s again working as new customer and add to cart ok. But after trying to add to cart after login it’s not working again.

    Can someone please help me on this matter?

  25. Benjamin

    Same probleme for me when accessing via the api soap.

    Fatal error: Call to a member function getPosition() on a non-object in \app\code\core\Mage\Bundle\Model\Product\Type.php on line 855

  26. Great post Branko! Question, is it possible to make the part apear in the cart for a specific customer through a SOAP API? I’ve tried to use api “cart_product.add” and it is going into the database properly (sales_flat_quote) but I am still not able to view it. Thanks

  27. Pammi

    Where should file will be placed or how to run this

  28. sajeena

    Can anyone help to get the SOAP API code for adding bundle products to cart.

Add Your Comment

Please wrap all source codes with [code][/code] tags.
Top