0

I am creating product custom options using the following code

foreach ($options as $arrayOption) {
    $product->setHasOptions(1);
    $product->setCanSaveCustomOptions(true);
    $option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
                            ->setProductId($product->getData('row_id'))
                            ->setStoreId(2)
                            ->addData($arrayOption);
    $option->save();
    $product->addOption($option);
}

But it is resulting in duplication of the same custom option enter image description here

There is a similar question but in magento 1: Product custom option duplication on save within loop

How to resolve the same for Magento 2?

1 Answer 1

0

Before addOption or save add if check

if(custom option exists){
continue;
}
else{
echo "continue what it is doing";
}

As you explained i hope when you are saving the option it will trigger both your methods save and create new custom option where your custom option is generating again. So you need to just add condition and restrict magneto if option exists then bypass the create new custom option method other wise create it.

Hope this helps.

2
  • I am adding the product options in a loop, so if my first option is set, it will show that the product's first option is set and will return true for $product->getOptions(). This does not allow me to add further options
    – GenZ Dev
    Mar 15, 2021 at 13:25
  • In your loop if option exists then return it other wise continue its work what ever is processing
    – Asad Ullah
    Mar 15, 2021 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.