Milind Daraniya

How to Get Item Customizable Option in Observer in Magento 2?

Published September 17th, 2023 10 min read

In Magento 2, customizable options allow customers to personalize products by selecting different attributes, such as size or color. If you want to perform specific actions based on these customizable options, you can utilize observers to capture and process the selected options. In this tutorial, we'll guide you through the process of getting item customizable options in an observer in Magento 2.

Step 1: Create an Observer

First, create an observer to capture the customizable options. In your custom module, define the observer in the etc/events.xml file:

<?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="custom_observer" instance="Vendor\Module\Observer\CustomObserver" />
    </event>
</config>

Step 2: Implement the Observer

In your custom module, create the CustomObserver.php file in the Observer directory:

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

class CustomObserver implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        $item = $observer->getEvent()->getData('quote_item');
        $product = $item->getProduct();

        // Get customizable options
        $customOptions = $product->getTypeInstance()->getOrderOptions($product);

        if (isset($customOptions['options'])) {
            foreach ($customOptions['options'] as $option) {
                // Process each customizable option
                $optionId = $option['option_id'];
                $optionValue = $option['value'];
                // Perform your desired actions here
            }
        }
    }
}

Step 3: Run the Observer

After implementing the observer, it will be triggered whenever a product is added to the cart. The observer will retrieve the selected customizable options for the added product and allow you to perform specific actions based on those options.

Using an observer to capture customizable options in Magento 2 enables you to respond to customer selections and personalize the shopping experience. You can utilize this functionality to implement various features, such as updating prices, applying discounts, or customizing product offerings based on the chosen options. Observers provide a flexible way to extend Magento's functionality and tailor it to your business needs.