Monday, 1 April 2019

Magento 2 : [SOLUTION] Add Bundle product into Cart Programmatically

We have created a script to add bundle product to the cart, programmatically adding all options to the bundle.

It's a simple code and its work perfectly.

create a text file in root directory and past the code then save and run in a browser. Then check the quote table.

test.php
<?php
ini_set('memory_limit','2048M');
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = true; // default false
$params[Bootstrap::PARAM_REQUIRE_IS_INSTALLED] = false; // default true

$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('global');

$quote = $obj->get('\Magento\Checkout\Model\Cart');

$product_id=66;
$_product = $obj->create('Magento\Catalog\Model\Product')->load($product_id);
 $selectionCollection = $_product->getTypeInstance(true)
                           ->getSelectionsCollection(
    $_product->getTypeInstance(true)->getOptionsIds($_product),$_product);
    // create bundle option
    $cont = 0;
    $selectionArray = [];
    $selectionqtyArray = [];
    $selectionpriceArray = [];
    foreach ($selectionCollection as $proselection){ 
       
                $selectionArray[$cont] = $proselection->getSelectionId();
                $selectionqtyArray[$cont] = $proselection->getSelectionQty();
                $selectionpriceArray[$cont] = $proselection->getPrice();
                $cont++;
            }
    // get options ids
    $optionsCollection = $_product->getTypeInstance(true)
                ->getOptionsCollection($_product);
   
    foreach ($optionsCollection as $options) {
           $id_option = $options->getId();
                }           
    // generate bundle_option array
    $bundle_option = [$id_option => $selectionArray];
    $bundle_qty = [$id_option => $selectionqtyArray];
    $bundle_price = [$id_option => $selectionpriceArray];
   
   
    $params = [
                'product' => $_product->getId(),
                'bundle_option' => $bundle_option,
                'bundle_option_qty' => $bundle_qty,
                'bundle_option_price' => $bundle_price,                           
                'qty' => 1,
                'original_qty' => 1
              ]; 
             
 $quote->addProduct($_product, $params);
 $quote->save();
//echo "<pre>";
//print_r($params);

?>

Please feel free to contact me any M1 & M2 issue at any time.


Regards
Kuldeep Singh
kuldeep4110@gmail.com