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 Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago