Update Individual Custom Option Value Programmatically in Magento 2

customizable-optionsmagento2

I'm using a script to programmatically update some products, bootstrapping Magento. I've had a lot of luck saving attributes using the product repository, when it comes to customizable options, I'm confused about the best way to update existing values.

I'm able to load up all of the options I need to update using Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory, but not sure how to save them from there.

Do you have to save option data as an array, or is it possible to update an individual field?

Best Answer

At first create an observer with event - catalog_product_save_before In the observer place the below code -

/** Dependency classes **/
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Product\OptionFactory;\

public function __construct( OptionFactory $productOptionFactory ) { $this->productOptionFactory = $productOptionFactory; }

$product = $observer->getEvent()->getProduct(); $exist = false; //check if the custom option exists foreach ($product->getOptions() as $option) { if ($option->getGroupByType() == ProductCustomOptionInterface::OPTION_TYPE_FIELD && $option->getTitle() == 'Custom Option') { $exist = true; } } if (!$exist) { try { $optionArray = [ 'title' => 'Custom Option', 'type' => 'field', 'is_require' => false, 'sort_order' => 1, 'price' => 0, 'price_type' => 'fixed', 'sku' => '', 'max_characters' => 0 ]; $option = $this->productOptionFactory->create(); $option->setProductId($product->getId()) ->setStoreId($product->getStoreId()) ->addData($optionArray); $product->addOption($option); } catch (\Exception $e) { //throw new CouldNotSaveException(__('Something went wrong while saving option.')); } }

Related Topic