1

I am working on updating custom options of an existing product programatically when admin click product save button -

I have done below code to full fil my desire -

app/code/Namespace/Module/etc/adminhtml/events.xml
 <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <!-- Admin Product Before save --> <event name="catalog_product_save_before"> <observer name="catalogProductSaveBefore" instance="Namespace\Module\Observer\Admin\catalogProductSaveBefore" /> </event> </config> 
app/code/Namespace/Module/Observer/Admin/catalogProductSaveBefore.php
 <?php namespace Namespace\Module\Observer\Admin; use Magento\Framework\Event\ObserverInterface; class CatalogProductSaveBefore implements ObserverInterface { protected $productRepository; protected $productCustomOptionInterface; public function __construct( \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Catalog\Api\Data\ProductCustomOptionInterface $productCustomOptionInterface ){ $this->productRepository = $productRepository; $this->productCustomOptionInterface = $productCustomOptionInterface; } public function execute(\Magento\Framework\Event\Observer $observer) { $product = $observer->getEvent()->getProduct(); if($product->getSubscriptionDisplayCalendar()){ $found=0; //0 if Custom Option not Found if($product->getOptions()){ foreach ($product->getOptions() as $opt){ if($opt->getTitle()=='Delivery'){ $found=1; // if Custom Option Found break; } } } if(!$found){ //if Not Found then create a new one $customOptions = array(); //Add New Custom Option not already exists $this->productCustomOptionInterface->setTitle('Delivery') ->setType('date') ->setIsRequire(true) ->setSortOrder(1) ->setPrice(0.00) ->setPriceType('fixed') ->setMaxCharacters(50) ->setProductSku(''); $customOptions[] = $this->productCustomOptionInterface; $product->setOptions($customOptions); } } else { if($product->getOptions()){ foreach ($product->getOptions() as $opt){ if($opt->getTitle()=='First Delivery'){ $opt->unsetOptions(); break; } } } } } } 

The above code should work , but its showing error, I also try to save product here but it hangs system.

Anyone has gone through like above condition? Still looking for update.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.