Back to Top

Magento2 Create Customer Checkout Quote and Add Products to that Quote

Updated 2 years ago

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(12490);
        $params = [
            "product" => "12490",
            "qty" => "1",
            "options" => [ //if product has options
                "10" => "19"
            ]
        ];
        $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($product, $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.

. . .

Leave a Comment

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


2 comments

  • senthli
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home