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.



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
) {
    $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->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.

| improve this answer | |
  • How can I do the same in .phtml file? – Chintan Kaneriya Oct 12 '18 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.