Magento – How to add bundle product to cart programmatically with custom price and quantity (of all products) in Magento 2

addtocartbundle-productcustom-optionsmagento2programmatically

I am struggling with Bundle Product add to cart programmatically in Magento 2.

Here I need to add all products with custom price and quantity and I want to do this operation in Product list.phtml file.

Can you help me with this, please?

Best Answer

Create a Controller

<?php

namespace Company\Module\Controller\Index;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Json as ResultJson;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;

class Addtocart extends Action
{
    /**
     * @var ProductFactory
     */
    private $productFactory;
    /**
     * @var Cart
     */
    private $cart;
    /**
     * @var FormKey
     */
    private $formKey;
    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @param Context $context
     * @param FormKey $formKey
     * @param JsonFactory $resultJsonFactory
     * @param Cart $cart
     * @param ProductFactory $productFactory
     */
    public function __construct(
        Context $context,
        FormKey $formKey,
        JsonFactory $resultJsonFactory,
        Cart $cart,
        ProductFactory $productFactory
    ) {
        parent::__construct($context);
        $this->formKey = $formKey;
        $this->productFactory = $productFactory;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->cart = $cart;
    }

    /**
     *
     * @return ResultJson
     */
    public function execute()
    {
        $data = $this->getRequest()->getParams();
        $resultData = [
            'status' => 'success',
            'status_code' => 1,
            'message' => __('Products Added successfully.')
        ];

        $result = $this->resultJsonFactory->create();
        $qty = 1;

        $product = $this->productFactory->create()->load($productId);
        $productsArray = $this->getBundleOptions($product);
        $params = [
            'product' => $productId,
            'bundle_option' => $productsArray,
            'qty' => $qty
        ];

        try {
            /**
             * Add bundle product in cart
             */
            if ($product->getId()) {
                $this->cart->addProduct($product, $params);
                $this->cart->save();
            }
        } catch (\Exception $e) {
            $resultData = [
                'status' => 'fail',
                'status_code' => 0,
                'message' => __('Unable to add the Product. Exception ' . $e->getMessage())
            ];
            return $result->setData($resultData);
        }
        return $result->setData($resultData);
    }

    /**
     * get all the selection products used in bundle product
     * @param $product
     * @return mixed
     */
    private function getBundleOptions(Product $product)
    {
        $selectionCollection = $product->getTypeInstance()
            ->getSelectionsCollection(
                $product->getTypeInstance()->getOptionsIds($product),
                $product
            );
        $bundleOptions = [];
        foreach ($selectionCollection as $selection) {
            $bundleOptions[$selection->getOptionId()][] = $selection->getSelectionId();
        }
        return $bundleOptions;
    }
}
Related Topic