Press ESC to close

How To Set Additional Options In Magento 2 Cart Item

Customizing your shopping cart can greatly enhance user experience, and one effective way to achieve this is by adding Additional Options in Magento 2. These options allow you to include tailored information, such as custom notes or product variations, directly in cart items. This not only ensures smoother communication with customers but also helps streamline the checkout process by capturing all necessary details upfront. Whether you’re managing a personalized product line or just looking to simplify customer interactions, integrating additional options in Magento 2 empowers your store to meet diverse business needs.

How to Add Additional Option in Cart Item

<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 the frontend side but won’t show in the admin order.

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

Append the 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
        
        }
      
    }
}

Setting additional options in Magento 2 cart items is a simple yet powerful way to enhance your e-commerce operations. This feature allows you to provide tailored shopping experiences, capture necessary details, and maintain order precision, all while improving customer satisfaction. By implementing this functionality, you can stay ahead in delivering customized services. If you need further assistance with Magento 2 features or customizations, consider partnering with an experienced e-commerce development company to unlock your store’s full potential.

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!

jhjbhjbhjbhjjjhbj

Share Post

Leave a Reply

Your email address will not be published. Required fields are marked *