Magento – Adding products to cart programmatically with custom price in controller: Magento 2

addtocartmagento2quotequoteitem

I am having a module that is creating quotes using the Magento quote module.

It is using the \Magento\Quote\Model\QuoteFactory for creating the quotes.

Now I have added a button "Proceed to checkout" that should add the quote items to the cart and the checkout page should be displayed to the user with those items that were in the quote.

Here I am creating the quotes as:

$quote = $this->quoteFactory->create()->load($quoteId);

The quotes are creating fine and I am getting the items in the quote as:

$items = $quote->getAllItems();

I am adding the products to cart as below,

$items = $quote->getAllItems();

foreach ($items as $item) {
    $formatedPrice = $item->getPrice();
    $quantity = $item['qty'];
    $productId = $item->getProductId();

    $params = array(
          'form_key' => $this->formKey->getFormKey(),
          'product' => $productId, //product Id
          'qty' => $quantity, //quantity of product
          'price' => $formatedPrice //product price
    );

    $_product = $this->_productRepository->getById($productId);

    if ($_product) {
        $this->cart->addProduct($_product, $params);
    }
}
try {
    $this->cart->save();
    $this->messageManager->addSuccess(__('Added to cart successfully.'));
} catch (\Magento\Framework\Exception\LocalizedException $e) {
    $this->messageManager->addException($e, __('%1', $e->getMessage()));
}

The issue here is the items are getting added into the cart but in case there are products that have a custom price, I need to add those products to the cart, with a different price to what is configured for the products in the catalog.

That custom price is defined in,

$formatedPrice = $item->getPrice();

Also, I am getting an issue where whenever I am creating a new quote and adding a previous quote to cart it is displaying the items for the latest quote that was created. How can this happen when the quote id is correct here?

I have referred a link that looks similar however, I need to implement the same in Magento 2.
https://stackoverflow.com/questions/5104482/programmatically-add-product-to-cart-with-price-change

Please, can anyone help me in achieving this?

Best Answer

Best way to add custom price using magento event.

You can see a code in below link.

https://easyprogramminglearning.blogspot.com/2019/01/magento2-add-custom-price-of-product.html

Related Topic