Programatically add bundle product to cart in Magento

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.

You made it all the way down here so you must have enjoyed this post! You may also like:

Allow backorders on a website scope Luka Rajcevic
Luka Rajcevic, | 4

Allow backorders on a website scope

Programmatically create bundle products in Magento Petar Sambolek
Petar Sambolek, | 5

Programmatically create bundle products in Magento

36 comments

  1. Hello, I hope anybody here has been through the scenario I am having…

    I want to add 2 independent simple products as single entry in cart with title like Product1 + Product2 and single total price of both against that entry…
    Quantity will remain 1

    Please guide.

  2. Well that does not solve the purpose for every bundle item with separate quantity each.
    for e.g.
    bundle 1
    ——————–
    item 1 -> quantity 5
    item 2->quantity 3
    is there any way to code that ?

  3. Well, that article is no help at all, how do I provide a working request array to the method addProduct of the Mage_Checkout_Model_Cart class for being able to add bundle products to the cart. You even don’t care to explain the bundle_option array and the ids there.

    I’m wondering about how even people can comment here that this is any help…

  4. I get this error now…

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

    Is there a way to fix this?

  5. 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

  6. 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

  7. 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?

  8. 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

  9. 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 ?

  10. 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?

  11. 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.

  12. 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

  13. 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”

  14. 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.

    1. Thanks , your code has help me a lot in bundle product itms qty.I was messing that how to set a bundle ootion qty to cart and your code has done my work.Thanks a lot man 🙂

  15. 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!!!!!!!!!!!!!

  16. 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!!!!!!!!!!!!!!

  17. 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.

  18. 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.

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

  20. 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!

  21. 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

  22. 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.

  23. 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

  24. 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.

  25. 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.

  26. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.