cancel
Showing results for 
Search instead for 
Did you mean: 

How to change item custom option in cart

How to change item custom option in cart

I have products with custom options. One of these products options must be updated just after product has been added to cart.

I then created an event launched just after "checkout_cart_add_product_complete".

My observer is called :

public function execute(\Magento\Framework\Event\Observer $observer) {

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Cart');
    $items = $cart->getQuote()->getAllItems();

    foreach ($items as $item)
    {
        $options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
        $customOptions = $options['options'];
        if (!empty($customOptions)) 
        {
            foreach ($customOptions as $key=>$option) 
            {
                if ($option['label']=="foo") 
                {
                    $options['options'][$key]['value']="bar";
                }
            }

            $cart->getquote()->getItemById($item->getItemId())->setOptions($options);
            $cart->save(); } } }

But when Cart is displayed, the product option has not been changed.

Thank you for your help,

2 REPLIES 2

Re: How to change item custom option in cart

Hi, you just need to use the same object $item to change options.

you can take existing options using 

$item->getOptions()

you can also take specific options with the method:

$item->getOptionByCode('code_string')

inside your foreach once you set your custom logic you can change option value using:

/** @var $serializer Magento\Framework\Serialize\SerializerInterface */
$itemOption = $item->getOptionByCode('code_string');
if (!empty($itemOption)) {
    $additionalOptions = $serializer->unserialize($itemOption->getValue());
    //Modify $additionalOptions array as needed
    $itemOption->setValue($this->serializer->serialize($additionalOptions))->save();
}

 

 

Re: How to change item custom option in cart

 

Hi, you need to use the below code for each item.

 

$items = $quote->getAllVisibleItems();
foreach ($items as $item) {
	$options = $item->getOptionByCode('additional_options');
	if (!$options) {

	    $additionalOptions = [
                'label' => 'Additional Option Label',
                'value' => 'Additional Option Value'
            ];
            $updateOptions = [
                'code' => 'additional_options',
                'value' => $this->serializer->serialize($additionalOptions)
            ];

            $item->addOption($updateOptions);
            $item->saveItemOptions();
	}
}