Read More
Read More
Menu Close

    Magento2 Create Customer Checkout Quote and Add Products to that Quote

    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.

    Searching for an experienced
    Magento 2 Company ?
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • senthli
    I want to add custom price to quote products, so that params i assigned price value, but the price is not set to the product
  • Back to Top