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

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…

3 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