How to add new custom options with custom values on cart update?

I have a custom HTML on cart page with some checkboxes.
I am getting All the selected checkboxes in my observer “checkout_cart_update_items_before” I am able to update cart item prices in this observer.

Now on cart update I want to create these selected checkboxes as Custom option to cart items and display them with all items in cart.

Following is the code that I have tried to create Custom options.

    $item->addOption(
                      array( 
                            'code'  => 'logo_options',
                            'value' => serialize($logo_positions),
                           )
                    );                      
    if ($logoOptions = $item->getOptionByCode('logo_options')) {                            
          $options = $item->getProductOptions();
          $options['logo_options'] = unserialize($logoOptions->getValue());
          item->setProductOptions($options);
    }
    $item->save();

Below is a screenshot of Cart.


enter image description here

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Try below code to save your custom options’ data.
You need to create arrays for each of the options you want to add to your product. I have used static data but you can do it with your dynamic data.

$logoOption = array(
    'label'                    => 'Logo Options',
    'option_value'             => 'My Logo',
    'value'                    => 'My Logo',
    'print_value'              => 'My Logo',
);
$locationOption = array(
    'label'                    => 'Location',
    'option_value'             => 'Right Breast',
    'value'                    => 'Right Breast',
    'print_value'              => 'Right Breast',
);
$value = array('logo_options'=> $logoOption, 'location' => $locationOption);
$value = serialize($value);

Now to set this data as Product options,
Use code,

$item->addOption(array('code'=> 'additional_options', 'product_id'=> $item->getProductId(), 'value'=> $value));

This will add your data to product as options. See screenshot.
enter image description here

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply