Magento2 – How to Add Product with Custom Options to Cart Programmatically

addtocartcustom-optionsmagento2

I want to add to cart product with custom options. I added simple product, but can't able to add with custom options.

How to do it ?

Please help me.

Thanks.

Best Answer

Try to use this code in your controller. It's for specific product. If you want to add multiple products. Then, you need to save multiple product collection in $product variable.

protected $formKey;
protected $_productFactory;
protected $_cart;
protected $messageManager;
protected $_url;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Framework\UrlInterface $url,
    \Magento\Framework\Message\ManagerInterface $managerInterface,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Checkout\Model\Cart $cart
) {
    parent::__construct($context);
    $this->formKey = $formKey;
    $this->_url = $url;
    $this->messageManager = $managerInterface;
    $this->_productFactory = $productFactory;
    $this->_cart = $cart;
}

public function execute()
{
    $product = $this->_productFactory->create()->load($productID);
    if ($product) {
        foreach ($product as $key => $value) {
            $custom_option_value = '';
            if (isset($value['super_attribute']) || !empty($value['super_attribute'])) {
                $custom_option_value = $value['super_attribute'];
            }
            $this->addCartProduct($value['id'], $value['qty'], $custom_option_value,$product);
        }
        $this->_cart->save();
    }
    $this->messageManager->addSuccess('Shopping cart updated succesfully.');
}

public function addCartProduct($productID, $productQty, $custom_option_val,$product)
{
    $info = new \Magento\Framework\DataObject(
        [
            'form_key' => $this->formKey->getFormKey(),
            'product_id' => $productID,
            'qty' => $productQty,
            'super_attribute' => $custom_option_val
        ]
    );
    return $this->_cart->addProduct($product, $info);
}

Hope, It will helpful for you.

Related Topic