How To Additional Options In Cart Item – Magento2

If you want to show any additional information in cart item then following code will help you out.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="set_additional_options"
        instance="Codedecorator\Learn\Observer\SetAdditionalOptions"/>
    </event>
</config>
namespace Codedecorator\Learn\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Serialize\SerializerInterface;

class SetAdditionalOptions implements ObserverInterface
{
    protected $request;
    private $serializer;

    public function __construct(
        RequestInterface $request,
        SerializerInterface $serializer
    )
    {
        $this->request = $request;
        $this->serializer = $serializer;
    }

    public function execute(EventObserver $observer)
    {
        $item = $observer->getQuoteItem();
        $post = $this->request->getPost();
		
        $additionalOptions = array();
        if ($additionalOption = $item->getOptionByCode('additional_options')) {
            $additionalOptions = $this->serializer->unserialize($additionalOption->getValue());
        }
        // check your custom condition
        if(isset($post['height'])){
			$price = 100;
            $additionalOptions[] = [
                'label' => 'Height',
                'value' => $post['height']
            ];
        }
         // Without any condition add option
         $additionalOptions[] = [
                'label' => 'CD',
                'value' => 'CD OPTION'
            ];

        if (count($additionalOptions) > 0) {
            $item->addOption(array(
                'product_id' => $item->getProductId(),
                'code' => 'additional_options',
                'value' => $this->serializer->serialize($additionalOptions)
            ));
        }
    }
}

Options will be shown on frontend side but wont show in admin order.

To set Additional in Order as well then go with following steps.

Append following code in events.xml that we have created

 <event name="sales_model_service_quote_submit_before">
        <observer name="order_add" instance="Codedecorator\Learn\Observer\SetAdditionalOptionsToOrder" />
 </event>
<?php

namespace Codedecorator\Learn\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Serialize\SerializerInterface;

class SetAdditionalOptionsToOrder implements ObserverInterface
{
    private $serializer;

    public function __construct(
        SerializerInterface $serializer
    )
    {
        $this->serializer = $serializer;
    }

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

            $quote = $observer->getQuote();
            $order = $observer->getOrder();

            foreach ($quote->getAllVisibleItems() as $quoteItem) {
              $quoteItems[$quoteItem->getId()] = $quoteItem;
            }

            foreach ($order->getAllVisibleItems() as $orderItem) {

                $quoteItemId = $orderItem->getQuoteItemId();
                $quoteItem = $quoteItems[$quoteItemId];
                $additionalOptions = $quoteItem->getOptionByCode('additional_options');

                if(!is_null($additionalOptions)) {
                    $options = $orderItem->getProductOptions();
                    $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
                    $orderItem->setProductOptions($options);
                }
            }
            return $this;

        }catch (\Exception $e) {
            
             // catch error if any
        
        }
      
    }
}

Happy coding 🙂

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Leave a Reply

Your email address will not be published.