I am having a module that is creating quotes using the Magento quote module.
Now I want to 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 (MagentoFrameworkExceptionLocalizedException $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 product 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 actually want to do something like this in Magento 2:
Programmatically add product to cart with price change
Please, can anyone help in figure this out?
2
Answers
Working solution and really easy if you think about it:
The missing pieces feel free to fill them in.
This worked for me in
Magento 2.2.8
:In a controller:
In
checkout_cart_product_add_after