Categories: How ToMagento 2

How to Add Additional Options in Magento 2

Being an Open source platform, Magento supports lots of customization and development. However, store owners are always in hunt of new feature and enhancement to existing Magento experience. Nowadays, lots of extensions are available in the market that will help store owners provide personalized experience. From landing onto the Magento store to the last step of product checkout, whole process plays a very important role for store owners in terms of providing great shopping experience for the products customers want to purchase. Default Magento supports various product types, but sometimes store owner needs to provide additional options to their customers to serve customized product and better service to the customer.

Recently, one of our clients willing to get various additional options from the customers so, he can easily deliver customized product fit to their requirements without affecting core Magento functionalities. After spending some time in coding, finally we have successfully delivered smile on a client’s face. But today I want to share that code with you guys.

First of all, we need to create two observer files and one Magento event file to implement this functionality. Basically, the Observer is a special class in Magento that executes whenever any an event gets fired.

Firstly, create events.xml file at Vendor/Extension/etc/events.xml and add below code into that file.



 
     
 
 
     
 

Once you have created this file, now you need to Create another file and named as CheckoutCartAddObserver.php at Vendor/Extension/Observer/CheckoutCartAddObserver.php

namespace Vendor\Extension\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
 
class CheckoutCartAddObserver implements ObserverInterface
{
 protected $_layout;
 protected $_storeManager;
 protected $_request;
    
    public function __construct(
     \Magento\Store\Model\StoreManagerInterface $storeManager,
     \Magento\Framework\View\LayoutInterface $layout,
     \Magento\Framework\App\RequestInterface $request
 )
 {
     $this->_layout = $layout;
     $this->_storeManager = $storeManager;
     $this->_request = $request;
 }
    
    public function execute(EventObserver $observer)
 {
     $item = $observer->getQuoteItem();
     $additionalOptions = array();
     if ($additionalOption = $item->getOptionByCode('additional_options')){
         $additionalOptions = (array) unserialize($additionalOption->getValue());
     }
     
     $additionalOptions[] = [
                 'label' => 'Additional Options Label',
                 'value' => 'Additional Options Value'
             ];
      }
     
     if(count($additionalOptions) > 0)
     {
         $item->addOption(array(
    'product_id' => $item->getProductId(),
             'code' => 'additional_options',
             'value' => serialize($additionalOptions)
         ));
     }
   
 }
}

Create another observer file named as QuoteSubmitObserver.php at Vendor/Extension/Observer/QuoteSubmitObserver.php

namespace Vendor\Extension\Observer;
 
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
 
class QuoteSubmitObserver implements ObserverInterface
{
 private $quoteItems = [];
 private $quote = null;
 private $order = null;
   
 public function execute(EventObserver $observer)
 {
     $this->quote = $observer->getQuote();
     $this->order = $observer->getOrder();
    
     foreach($this->order->getItems() as $orderItem)
     {
       if($quoteItem = $this->getQuoteItemById($orderItem->getQuoteItemId()))
       {
                 if ($additionalOptionsQuote =        $quoteItem->getOptionByCode('additional_options'))
                 {
                    
         if($additionalOptionsOrder = $orderItem->getProductOptionByCode('additional_options'))
                     {
                         $additionalOptions = array_merge($additionalOptionsQuote, $additionalOptionsOrder);
                     }
                     else
                     {
                         $additionalOptions = $additionalOptionsQuote;
                     }
                     if(count($additionalOptions) > 0)
                     {
                         $options = $orderItem->getProductOptions();
                         $options['additional_options'] = unserialize($additionalOptions->getValue());
                         $orderItem->setProductOptions($options);
                     }
 
                 }
             }
     }
 }
 private function getQuoteItemById($id)
 {
     if(empty($this->quoteItems))
     {
         
         foreach($this->quote->getItems() as $item)
         {
             $this->quoteItems[$item->getId()] = $item;
         }
     }
     if(array_key_exists($id, $this->quoteItems))
     {
         return $this->quoteItems[$id];
     }
     return null;
 }
} 

Once you have created both the file at desired location, an additional option will visible to your Magento front-end. You can even customize this code according to your need of adding additional options. If you are facing any issue while implementing this code or to have some talk about this blog, don’t forget to leave comments below & to share this article with your Magento friends.
And Yeah ! hit the starts below if this code helped you to implement additional options.

Happy Coding !

Click to rate this post!
[Total: 18 Average: 4.5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

2 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

4 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

4 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

5 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

6 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago