Question

i have tried with add to cart with multiple products simple, config, virtual all types of product but i am not able to add multiple product. You can see below code of add to cart product.

$product = Array
(
 [0] => Array
    (
        [id] => 1
        [qty] => 1
        [type] => simple
    )

[1] => Array
    (
        [id] => 27
        [qty] => 1
        [type] => configurable
        [options] => Array
            (
                [135] => 4
                [93] => 10
            )

    )

[2] => Array
    (
        [id] => 10
        [qty] => 1
        [type] => downloadable
        [link] => Array
            (
                [links] => Array
                    (
                        [0] => 7
                        [1] => 8
                    )

            )

    )

)
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$quote = $objectManager->get('\Magento\Checkout\Model\Cart');
foreach ($product as $key) {
        $_product = '';
        $_product = $objectManager->get('\Magento\Catalog\Model\Product')->load($key['id']);
        if($key['type']=='simple' || $key['type']=='virtual'){
            $params = array (
                'product' => $key['id'],
                'qty' => $key['qty']
            );
        } 
        if ($key['type']=='downloadable') {
            $params = array (
                'product' => $key['id'],
                'qty' => $key['qty'],
                'links' => $key['link']
            );
        } 
        if ($key['type']=='configurable') {
            $params = array (
                'product' => $key['id'],
                'qty' => $key['qty'],
                'super_attribute' => $key['options']
            );
        }
        $quote->addProduct($_product, $params);
    }
    $quote->save(); 

This whole code working with one type of product but there is not working with multiple product type.

can you please suggest how can i resolve the issue ?

Was it helpful?

Solution

Try to change

$_product = $objectManager->get('\Magento\Catalog\Model\Product')->load($key['id']);

With

$_product = $objectManager->create('\Magento\Catalog\Model\Product')->load($key['id']);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top