Magento – Add to cart bundle product programatically magento 2

addtocartbundled-productmagento2product

I tried with add to cart bundle product but getting error when run the custom code. you can see below code for bundle product.

    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
    $quote = $objectManager->get('\Magento\Checkout\Model\Cart');
    $_product = $objectManager->get('\Magento\Catalog\Model\Product')->load(28);
    $params = array (
        'product' => 28, // product id
        'qty' => 1, // product qty
        'related_product' => null,
        'bundle_options' => array(
            6 => 1, // 6 is bundle sub product id and 1 is option id
            2 => 2
        )
    );

    $quote->addProduct($_product, $params);
    $quote->save();

and when i run the custom above code you can see below error.

1 exception(s):
Exception #0 (Magento\Framework\Exception\LocalizedException): Please specify product option(s).

can you please suggest what is the issue on code.
Thanks

Best Answer

You have to change your bundle_options array, in fact in magento 2, you have to insert the field "selection_id" and not sub product id.

Below you can find my code to how i resolve it (in this case i use only one multiselect option):

// get selection option in a bundle product
$selectionCollection = $_product->getTypeInstance(true)
                       ->getSelectionsCollection(
$_product->getTypeInstance(true)->getOptionsIds($_product),$_product);
// create bundle option
$cont = 0;
$selectionArray = [];
foreach ($selectionCollection as $proselection){                        
            $selectionArray[$cont] = $proselection->getSelectionId();
            $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]];

$params = [
            'product' => $id,
            'bundle_option' => $bundle_option,
            'qty' => 1
          ];                

$this->cart->addProduct($_product, $params);

The bundle_option results like below:

$bundle_option = array (9 =>  // this is option id
                   array (0 => // this is a simple counter
                     array (0 => '42', // 42 is selection_id
                            1 => '43', // 43 is second selection_id
                           ),
                         ),
                 ) 

I hope that i can help you.

Related Topic