Magento – Magento2 : How to add a custom option to Item in cart

cartcustom-optionsmagento2

I have product with a custom option.

On the event checkout_cart_product_add_after, I want to assign to this option some value programmatically.
If the option has been set by the customer in product page, I manage to do it using :

$this->_cart->getquote()->getItemById($item->getItemId())->getOptionByCode('option_'.$OptionID)->setValue($foo)->save();

But in the case the option has not been set by customer in product page, the cart item does not have this option. I then need to create it, but I do not manage to do it.

NB: I can retreive the product options using :

$ProductId=$item->getProduct()->getId();
$Product=$this->_productRepository->getById($ProductId);
$Options=$Product->getOptions();

Thank you for your help

Best Answer

you have to change your code in observer file

    public function execute(Observer $observer) {

        $item  = $observer->getEvent()->getData('quote_item');          
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );

        $_product = $item->getProduct();

        $options  = $_product->getTypeInstance(true)->getOrderOptions($_product);

        $customOptions = $options['options'];

        $foo = black; //fill custom value here

        foreach($customOptions as $key=>$option):        

            if($option[label]==Color):
              $item->getOptionByCode('option_'.$option['option_id'])->setValue($foo);
            endif;

        endforeach;     
    }

its perfectly working for me. hope this will help you. i know its too late but its helpful for anyone needed.

Happy Coding

Related Topic