Magento 2 – Add Multiple Configurable Product Variations to Cart

magento2multiple-add-to-cart

I'm trying to add multiple variations of a configurable product to the cart at once, and I've put the code together, but currently it's adding the right qty of products, but only using the first variation.

In other words, if I try to add 2 Green T-Shirts and 4 White T-Shirts, It's adding 6 Green T-Shirts into cart.

This is the code I've got inside add controller:

public function execute()
    {
        $paramsData = $this->getRequest()->getParams();
        try {
            $msg = array();
            $errorMsg = array();
            foreach($paramsData['qty'] as $pId=>$param){ 

                if (isset($param)) {
                    $filter = new \Zend_Filter_LocalizedToNormalized(
                        ['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()]
                    );
                    $params['qty'] = $filter->filter($param);
                }

                $params['product'] = $paramsData['product'][$pId];
                $product = $this->initProduct($params['product']);   
                $params['super_attribute'] = $paramsData['super'][$pId]; 
                /**
                 * Check product availability
                 */
                if (!$product) {
                    return $this->goBack();
                }            

                $this->cart->addProduct($product, $params);
                $msg[] = $product->getName(); 
            }             

            $this->cart->save();

        }         
        $resultRedirect->setPath('checkout/cart');
        return $resultRedirect;
    }

And from that print_r, it's confirming that the options are correct:

 Array ( [super_attribute] => Array ( [90] => 5 ) [qty] => 2 ) 

 Array ( [super_attribute] => Array ( [90] => 7 ) [qty] => 4 ) 

But in the cart I'm seeing 6 of the first super_attribute(6 green T-Shirts instead of 2 green and 4 white t-shirt).

Is there something I need to do to 'reset' the cart after adding each item or something?

Thanks.

Best Answer

I have got answer, issue is product object override next loop, in controller,

we have to create each time new product object and now its working after doing below changes.

Instead of $product = $this->initProduct($params['product']);we have set below line,

$storeId = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
$product = $this->_objectManager->create('Magento\Catalog\Model\Product')->setStoreId($storeId)->load($params['product']);

Its works.

Related Topic