I have the same problem as mentioned in this Question: Magento 2: Add multiple products to cart programmatically But it was never answered. This is my Controller.php:
<?php
namespace MassiveArt\ShoppingCart\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class Index extends Action
{
/**
* @var FormKey
*/
protected $formKey;
/**
* @var Session
*/
protected $checkoutSession;
/**
* @var Cart
*/
protected $cart;
/**
* @var Product
*/
protected $product;
/**
* Constructor.
*
* @param Context $context
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Customer\Model\Session $customerSession
* @param JsonFactory $resultJsonFactory
* @param FormKey $formKey
* @param Cart $cart
* @param Product $product
*/
public function __construct(
Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Customer\Model\Session $customerSession,
JsonFactory $resultJsonFactory,
FormKey $formKey,
Cart $cart,
Product $product
) {
$this->checkoutSession = $checkoutSession;
$this->customerSession = $customerSession;
$this->formKey = $formKey;
$this->resultJsonFactory = $resultJsonFactory;
$this->cart = $cart;
$this->product = $product;
parent::__construct($context);
}
public function execute()
{
try {
// Set result data and pass back
$result = $this->resultJsonFactory->create();
if(!$this->customerSession->getCustomer()->getId()) {
$result->setData(['error' => __('Invalid session ID')]);
}
// Get parameters
$productIds = $this->getRequest()->getParam('productIds');
$amounts = $this->getRequest()->getParam('amounts');
for ($i = 0; $i < count($productIds); $i++) {// Load product by ID
$product = $this->product->load($productIds[$i]);
// New product params
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productIds[$i],
'qty' => $amounts[$i],
);
// Save Product
$product->save();
// Add product to cart
$this->cart->addProduct($product, $params);
}
//Save cart
$this->cart->save();
$result->setData(['message' => __("Products added succesfully")]);
return $result;
} catch(\Exception $e) {
$result->setData(['error' => __($e->getMessage())]);
return $result;
}
}
}
The code works fine, if the cart is not empty, but if the cart is empty only one product is added to cart with sum of quantity for all the product.
For eg if I add: Prod 1 - 2 quantity Prod 2 - 1 quantity Cart will contain prod 1 with 3 quantity.
Please let me know how to solve this.