1

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 ?

2
  • 1
    Please review link Oct 10, 2017 at 7:27
  • @PurushotamSharma thanks but in this link product adding to current cart ... i want load custom card by customer id Oct 10, 2017 at 7:33

1 Answer 1

6

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 !!

6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.