Step 1: Create registration.php and module.xml file the for custom module.
Step 2: Assign Observers to Events
/app/code/Namespace/Mymodule/etc/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_product_load_after">
<observer name="set_additional_options" instance="Namespace\Mymodule\Observer\SetAdditionalOptions"/>
</event>
</config>
Step 3: Create the Observers
app/code/Namespace/Mymodule/Observer/SetAdditionalOptions.php
<?php
namespace Namespace\Mymodule\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Serialize\SerializerInterface;
class SetAdditionalOptions implements ObserverInterface
{
/**
* @var RequestInterface
*/
protected $_request;
/**
* @param RequestInterface $request
*/
public function __construct(
RequestInterface $request,
SerializerInterface $serializer
) {
$this->_request = $request;
$this->serializer = $serializer;
}
/**
* @param \Magento\Framework\Event\Observer $observer
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
// Check and set information according to your need
if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
$product = $observer->getProduct();
$additionalOptions = [];
$additionalOptions[] = array(
'label' => 'Some Label',
'value' => 'Some Info',
);
$observer->getProduct()->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
}
}
}
run below command after
rm -rf var/di var/generation var/cache/* var/log/* var/page_cache/*
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento indexer:reindex
reference links
https://www.cloudways.com/blog/add-additional-options-in-magento-2/
https://webkul.com/blog/additional-options-cart-item-magento2/
https://www.codedecorator.com/blog/how-to-additional-options-in-cart-item-magento2/ (Magento2.4)