TransWikia.com

Add option to product in the cart progrmatically in magento 2

Magento Asked by anantchopra2007 on September 12, 2020

<?php
namespace NeologixBopisObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoCheckoutModelSession as CheckoutSession;

class SetAdditionalOptions implements ObserverInterface
{

    protected $_request;

    public function __construct(
        RequestInterface $request,CheckoutSession  $checkoutSession
    ) {
        $this->_request = $request;
        $this->checkoutSession = $checkoutSession;
    }
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $infoDataObject = $observer->getEvent()->getInfo()->toArray();
        $cart = $observer->getEvent()->getCart();

        foreach ($infoDataObject as $itemId => $itemInfo) {

           $item = $cart->getQuote()->getItemById($itemId);
           $product = $item->getProduct();
           **// able to load product but after this code is not working for adding options to the product**
           $additionalOptions = array(
                array(
                    'code'  => 'my_code',
                    'label' => 'This text is displayed through additional options2',
                    'value' => 'ID is '
                )
            );
             $product->addOption(
                array(
                     'code'  => 'additional_options',
                     'value' => serialize($additionalOptions),
                )
            );
        }
    }
}
?>

2 Answers

Try his code. It will work

       $additionalOptions[] = [
                'label' => 'This text is displayed through additional options2',
                'value' => 'ID is '
            ];

        if(count($additionalOptions) > 0){
            $item->addOption(array(
                'code' => 'additional_options',
                'value' => serialize($additionalOptions)
            ));
        }

Answered by Gurdit Singh on September 12, 2020

try below event for your task

checkout_cart_update_items_before

because right now when you adding product option but quote is already updated so if you are setting up the custom option they are not getting saved

So use before event instead of after

you can see more info in this class

https://github.com/magento/magento2/blob/2.0.13/app/code/Magento/Checkout/Model/Cart.php

Answered by Murtuza Zabuawala on September 12, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP