How to add additional options in magento 2 cart

Written by Jigar Patel

Oct 25, 2021

How to add additional options in magento 2 cart

Magento 2 is an e-commerce platform that improves the shopping cart. Magento supports lots of customization and development. Recently, one of our clients was willing to add additional options from the customers so, he can easily deliver customized products fit to their requirements without changing core Magento functionalities. After spending some time coding, finally, we have successfully delivered a smile to a client’s face. But today I want to share that code with you guys.

We are already learned how to create a basic module in Magento 2. We need to create module.xml and registration.php files. You can create module.xml and registration.php from this tutorial.

Here we are using Dolphin as Vendor name and Additional as the name of the module.  You can change this according to your Vendor and Module name.

Step 1: Create Events XML File

The first thing you need to do is to create an events.xml file in the folder Dolphin/Additional/etc/ and use the first event checkout_cart_product_add_after  which will be called after adding a product to the cart and second event sales_model_service_quote_submit_before which will be called quote submit before.

<?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="checkout_cart_product_add_after">
        <observer name="dolphin_checkout_cart_product_add_after"
                  instance="Dolphin\Additional\Observer\CheckoutCartAdd"/>
    </event>
    <event name="sales_model_service_quote_submit_before">
        <observer name="dolphin_add" instance="Dolphin\Additional\Observer\AddOptionToOrder"/>
    </event>
</config>

Here you declare the first observer named CheckoutCartAdd that will handle the event checkout_cart_product_add_after which Magento dispatches every time a product’s added to the cart and declare the second observer named AddOptionToOrder that will handle the event sales_model_service_quote_submit_before which Magento dispatches every time a quote submit before.

Now we need to create an Observer as defined in the events.xml file

Read This: Magento 2 add ifconfig in override block XML

Step 2: Create CheckoutCartAdd.php File

Create observer class file CheckoutCartAdd.php in app/code/Dolphin/Additional/Observer folder with the following code.

<?php

namespace Dolphin\Additional\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Serialize\SerializerInterface;

class CheckoutCartAdd implements ObserverInterface
{
    protected $layout;
    protected $storeManager;
    protected $request;
    private $serializer;

    public function __construct(
        StoreManagerInterface $storeManager,
        LayoutInterface       $layout,
        RequestInterface      $request,
        SerializerInterface   $serializer
    )
    {
        $this->layout = $layout;
        $this->storeManager = $storeManager;
        $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());
        }

        $additionalOptions[] = [
            'label' => 'Option Label',
            'value' => 'Option Value'
        ];

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

Step 3: Create AddOptionToOrder.php File

Create observer class file AddOptionToOrder.php in app/code/Dolphin/Additional/Observer folder with the following code.

<?php

namespace Dolphin\Additional\Observer;

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

class AddOptionToOrder implements ObserverInterface
{
    private $serializer;

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

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if ($this->helperData->isModuleEnabled()) {
            $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 (count($additionalOptions) > 0) {
                    $options = $orderItem->getProductOptions();
                    $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
                    $orderItem->setProductOptions($options);
                }
            }

            return $this;
        }
    }
}

Result :

How to add additional options in magento 2 cart

I Hope, This instruction will be helpful for you.

If you have any difficulties regarding this blog, do consider them posting in the Comments section below!

I’m here to help.

Thank you!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP