I want to add a product to customer cart by product id and customer id
I think that way should be like this
load quote session and set customer id and then add product .
can you help me to do this ?
I want to add a product to customer cart by product id and customer id
I think that way should be like this
load quote session and set customer id and then add product .
can you help me to do this ?
Use below code to add product into cart using customer Id and Product Id
public function __construct(
/* Add below dependencies */
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
\Magento\Quote\Model\Quote $quoteModel,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
$this->storeManager = $storeManager;
$this->_customerRepositoryInterface = $customerRepositoryInterface;
$this->quoteModel = $quoteModel;
$this->productRepository = $productRepository;
}
Add below code in your existing function:
try {
$customer = $this->_customerRepositoryInterface->getById($customerId);
$quote = $this->quoteModel->loadByCustomer($customer);
if (!$quote->getId()) {
$quote->setCustomer($customer);
$quote->setIsActive(1);
$quote->setStoreId($this->storeManager->getStore()->getId());
}
$product = $this->productRepository->getById($productId);
$quote->addProduct($product, $qty);
$quote->collectTotals()->save();
} catch (\Exception $e) {
//echo $e->getMessage(); die;
}
Updated
For adding the multiple products into cart, You can use like below where $products is array of product Ids.
foreach ($products as $productId) {
$product = $this->productRepository->getById($productId);
if ($product->getId() && $product->isVisibleInCatalog()) {
try {
$request = new \Magento\Framework\DataObject(['qty' => 1]);
$quote->addProduct($product, $request);
$count++;
} catch (\Exception $e) { }
}
}
$quote->collectTotals()->save();
Hope this help !!