Add Configurable Product to Cart Programmatically – Magento 2 Guide

addtocartconfigurable-productmagento2superattribute

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.

protected $_cart;
protected $productRepository;

public function __construct(
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
)
{
    $this->_cart = $cart;
    $this->productRepository = $productRepository;
}

...
...

$productId = 10; // enter your product_id
$qty = 1; // enter number of quantites you want to add

/*
I am using below ids as configurable options for example purpose only.
You have to use your attribute id and option id.

90 = attribute_id of color 
53 = option_id of any specific color,

143 = attribute_id of size
170 = option_id of any specific size
*/

$options = array(
                90 => 53,
                143 => 170
            );

$params = array(
    'product' => $productId,
    'super_attribute' => $options,
    'qty' => $qty
);

$_product = $this->productRepository->getById($productId);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();

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/