How To

Magento 2: Display Programmatically Created Custom Options in Admin Order Details

Hello Magento Folks,

Hope you are all doing well, I am back with another exciting article on Magento 2 How to Series. Last time we learned about Magento 2: How to Add New Column In The Customer Grid. So today, We will learn how to display programmatically created custom options in admin order details Magento 2.

Introduction

Kindly, check this article for How to add Custom Options to the Product Programmatically in Magento 2. In case your thinking to learn about how to display programmatically created custom options in admin order details in Magento 2. Then this is the right spot for you to learn that. In Magento 2, the custom option feature is an inherent feature available; this option will grant permission to customers to customize the product according to their need within the given different custom options. If you want to display programmatically created custom options in admin order details programmatically, you have to follow the instructions provided below.

Let’s Find Out Programmatically Solutions:

Step 1: Create VENDOR\EXTENSION\etc\events.xml

<?xml version=&quot;1.0&quot;?>
<config xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:noNamespaceSchemaLocation=&quot;urn:magento:framework:Event/etc/events.xsd&quot;>
<event name=&quot;sales_model_service_quote_submit_before&quot;>
<observer name=&quot;quote_to_order&quot;
instance=&quot;VENDOR\EXTENSION\Observer\OrderItemAdditionalOptions&quot; />
</event>
</config>

Step 2: Create an observer for it.

Create VENDOR\EXTENSION\Observer\OrderItemAdditionalOptions.php

<?php
namespace VENDOR\EXTENSION\Observer;
use Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\Unserialize\Unserialize;
use \Magento\Framework\Serialize\Serializer\Json;
class OrderItemAdditionalOptions implements ObserverInterface
{
    /**
     * @param \Magento\Framework\Event\Observer $observer
     */    protected $Unserialize;
    protected $Serializer;
    public function __construct(
        Unserialize $Unserialize,
        Json $Json
    ){
        $this->Unserialize = $Unserialize;
        $this->Serializer = $Json;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            $quote = $observer->getQuote();
            $order = $observer->getOrder();
            $quoteItems = [];
   // Map Quote Item with Quote Item Id
            foreach ($quote->getAllVisibleItems() as $quoteItem) {
                $quoteItems[$quoteItem->getId()] = $quoteItem; //130
            }
            foreach ($order->getAllVisibleItems() as $orderItem) {
                $quoteItemId = $orderItem->getQuoteItemId();
                $quoteItem = $quoteItems[$quoteItemId];
                $additionalOptions = $quoteItem->getOptionByCode('additional_options');
     // Get Order Item's other options
                    $options = $orderItem->getProductOptions();
                    // Set additional options to Order Item
                   if($this->isSerialized($additionalOptions->getValue())){
                        $options['options'] = $this->Unserialize->unserialize($additionalOptions->getValue());
                   }else{
                    $options['options'] = $this->Serializer->unserialize($additionalOptions->getValue());
                   }
                    $orderItem->setProductOptions($options);
            }
        }
        catch (\Exception $e) {
            // catch error if any
            $e->getMessage();
        }
    }
    private function isSerialized($value)
    {
        return (boolean) preg_match('/^((s|i|d|b|a|O|C):|N;)/', $value);
    }
}
?>

Conclusion

That’s it for today! Now, you can easily display programmatically created custom options in admin order details by just following the above given easy steps.

Last but not least, if you found the blog interesting, don’t forget to share with your Magento pals. Feel free to Contact Us if you find any difficulty in applying the above steps.

Happy Coding!?

Click to rate this post!
[Total: 6 Average: 4.7]
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

  • I used this code. It is working fine for adding string custom option, but getting error as "Type Error occurred when creating object: Magento\Framework\Filter\TruncateFilter\Result, Argument 1 passed to Magento\Framework\Filter\TruncateFilter\Result::__construct() must be of the type string, array given" to adding images (type: image)

  • i used this code, but it not proper working for configurable product.i am placing two product.it display custom option for first product not showing for second product.

    • You need to fetch that additional_options data by loading the order by order Id or something.

Recent Posts

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…

2 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…

2 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…

3 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…

4 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.…

6 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

6 days ago