0

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

4
  • You can take reference from here. It's working. magento.stackexchange.com/a/243628/51810 Oct 2 '18 at 8:34
  • Is it useful for you? Oct 2 '18 at 8:52
  • Thank you for your answer. No it does not help me. Product is already added to cart in my case. I would like something like : $item->setProductrOption($OptionID, $Optionvalue)
    – Alexglvr
    Oct 2 '18 at 10:50
  • Did you ever find a solution to this? May 19 '19 at 14:50
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.