Here we will learn, how in Magento2 Create Customer Checkout Quote and Add Products to that Quote.
I have created a demo class here:
<?php namespace Webkul\Test\Model; class CustomAddToCart { public function __construct( \Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Customer\Model\Session $customerSession, \Magento\Quote\Api\CartManagementInterface $quoteManagement, \Magento\Quote\Api\CartRepositoryInterface $quoteRepository ) { $this->productFactory = $productFactory; $this->quoteManagement = $quoteManagement; $this->quoteRepository = $quoteRepository; $this->_customerSession = $customerSession; } public function quoteAddToCart() { $customerId = $this->_customerSession->getCustomerId(); // let's assume product Id is 50 $product = $this->productFactory->create()->load(50); $params = [ "product": "50", "qty": "1", "options": [ //if product has options "4": "8", "5": "10", ] ]; $request = new \Magento\Framework\DataObject(); $request->setData($params); // here quote is created for customer $quoteId = $this->quoteManagement->createEmptyCartForCustomer($customerId); $quote = $this->quoteRepository->get($quoteId); $quote->addProduct($productAddToCart, $request); $this->quoteRepository->save($quote); $quote->collectTotals(); } }
In above snippet you can see i have created the quote by customer id using
createEmptyCartForCustomer() method, it will return new Quote Id.
2 comments
Set custom price of Product when adding to cart