Add bundle Items with a checkbox option to cart programmatically

Here we are checking the product type and adding the product to the cart programmatically based on the bundle item as the checkbox item.

$productModel = $this->product->create();
            $productModel->load($item->getProductId());
            $productinfo = $this->product->create()->load($item->getProductId());
            $productType = $productinfo->getTypeID();
            if ($productType == "bundle") {
                $selectionCollection = $productinfo->getTypeInstance(true)
                    ->getSelectionsCollection(
                        $productinfo->getTypeInstance(true)->getOptionsIds($productinfo), $productinfo);    // create bundle option
                $logger->info("bundle1");
                $cont = 0;
                $selectionArray = [];
                foreach ($selectionCollection as $proselection) {
                    $selectionArray[$cont] = $proselection->getSelectionId();
                    $cont++;
                }
                $logger->info("bundle2");       // getting product_options here
                $optionsCollection = $productinfo->getTypeInstance(true)
                    ->getOptionsCollection($productinfo);

                foreach ($optionsCollection as $options) {
                    $id_option = $options->getId();
                }
                $bundle_option = [$id_option => [$selectionArray]]; // generate bundle_option array_options here
                $options = [
                    'product' => $item->getId(),
                    'bundle_option' => $bundle_option,
                    'qty' => $item->getQty()
                ];
                $this->cart->addProduct($productModel, $options);
                $logger->info(print_r($bundle_option,true));
            } else {
            $this->cart->addProduct($productModel, $productData); //for normal simple items in else condition
        }

Leave a comment

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