I tried with add to cart configurable product but getting error when run the custom code using observer but same code when run from controller than it's working fine. 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(27);
$params = array (
'product' => 27, // product id
'qty' => 1, // product qty
'related_product' => null,
'super_attribute' => array(
6 => 1, // 6 is attribute id and 1 is index_value
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): You need to choose options for your item.
Best Answer
Here I am using the example of color and size attributes.
Note: Programatically added product to cart will not be visible in minicart. Check your added products in shopping cart page. If you want to update your minicart after adding product programatically, Please visit below link
https://webkul.com/blog/update-cart-adding-product-programmatically-magento2/