Programmatically Add More Product With Custom Options To An Existing Quote In Magento 2:- In this blog we will see how we can add product with custom option to an existing quote.
For Simple Type product you can check : Programmatically Add More Product To An Existing Quote In Magento 2
To add product with custom options to an existing quote follow below steps:
$productId = 12; // assign product Id
$qty = 2; // assign product quantity which you want to add
//Get quote from checkout session
$session = $this->checkoutSession->create(); //checkoutSession is an instance of \Magento\Checkout\Model\SessionFactory
$quote = $session->getQuote();
$product = $this->productRepository->getById($productId); // _productRepository is an instance of \Magento\Catalog\Api\ProductRepositoryInterface
//prepare customOption and add
//here json is instance of \Magento\Framework\Serialize\Serializer\Json
$product->addCustomOption('additional_options', $this->json->serialize([
'custom_option_1' => [
'label' => __("Custom Option 1"),
'value' => 10
],
'custom_option_2' => [
'label' => __("Custom Option 2"),
'value' => 20
],
]));
$quote->addProduct($product, $qty);
$this->cartRepository->save($quote); //cartRepository is an instance of \Magento\Quote\Api\CartRepositoryInterface
$session->replaceQuote($quote)->unsLastRealOrderId();
In this way we can more product with custom options to an existing quote in magento2. Hope it will be helpful for you. If you have any query then comment below.
Thankyou!
3 comments
In case of multiple product you have to follow all the steps again. Or you can just create a method or function suppose addToCart() and then call this method in loop with different product options.
Hope now you got your answer and in case if you still facing issue then comment below.