Create custom options in event observer magento 2
-
01-10-2020 - |
Question
I want to create new custom option for quote item in my observer. How can I do that? Here is my code:
public function execute(\Magento\Framework\Event\Observer $observer) {
$item = $observer->getEvent()->getData('quote_item');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = '100'; //set your price here
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}
I am setting custom price but I also need to set some custom options. I have created observer on checkout_cart_product_add_after event.
Solution
You can use catalog_product_type_prepare_full_options
event if you want to set custom option
In this event you can easily get $product
object by using
$product = $observer->getEvent()->getProduct();
set your custom option by
$infoOptions[] = array(
'label' => "YOUR_LABEL",
'value' => "YOUR_VALUE",
);
Add this custom option by
$product->addCustomOption('additional_options', serialize($infoOptions));
just it,
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange