Magento 2 – Getting Selected Custom Option Value for a Product

cartcustom-optionsevent-observermagento-2.0magento2

I need to get the selected custom option value of product added in the cart. To observe the product add to cart, i have used an event checkout_cart_product_add_after

In the observer, I have loaded the product using below code:

$item = $observer->getEvent()->getData('quote_item');
$product = $observer->getEvent()->getData('product');

I am able to get product quantity added to the cart using $product->getQty() however, i am not getting the values of selected custom option.

By using below code i can get all the custom options for product

foreach($product->getOptions() as $o){
        $optionType = $o->getType();
        foreach($o->getValues() as $value){
            echo "<pre>";
            print_r($value->getData());
            echo "</pre>";
        }
}

Can anyone please guide how to get selected option value.

[Edit]

As per the answer by Raphael, i observed an event catalog_product_type_prepare_full_options and got the value of selected option for the product.

Now, my problem is i need to pass these values to the observer i have created for checkout_cart_product_add_after. The reason behind this is, I am trying to add a product into cart when certain product with selected custom option is added to the basket.

Is there a way to pass these value to my observer or any better/correct solution for this.

Best Answer

I was not able to get the selected custom option on event checkout_cart_product_add_after

however, i was successful in getting the values using checkout_cart_save_before event.

For those who might need it in future. The code for retrieving the custom options is as below:

public function execute(\Magento\Framework\Event\Observer $observer) {  
    /* Fetches data of items available in cart. */
    $cart = $observer->getEvent()->getData('cart');
    $cartItems = $cart->getItems();

    foreach($cartItems as $item){
        //here you do what you want with the product.
        $_customOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()); 
        if(array_key_exists('options', $_customOptions)){
            //print_r($_customOptions);
            foreach($_customOptions['options'] as $option){
                print_r($option);
            }
        }
    }
}

Hope it helps. I am accepting this answer as this is the closest I could get to. I will be happy to accept the solution if someone posts it.

Related Topic