4

I have added the custom option programatically following this . Not everything worked but I made few changes and successfully added the custom option programatically. But I couldn't get that custom option displayed on frontend. On further checking I figure out there is a problem while setting the hasOptions().

I tried below codes to set has options

$_products = $this->_objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$_products->setHasOptions(1);
$_products->save();

Also tried this

$_products = $this->_objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$_products->setHasOptions(1);
$_products->getResource()->save();

But I couldn't get it working.

Can anyone help.

3 Answers 3

4

You need to set the following instead of setHasOptions(1):

$product->setData('can_save_custom_options', 1);

Then the has_options field will be set to 1 automatically when you are saving options.

1
  • 1
    Excellent.. this is exactly work as per the above..!! Commented Jan 29, 2020 at 11:27
0

Check method \Magento\Catalog\Model\Product::beforeSave(). At the begin of method is this code:

    $this->setTypeHasOptions(false);
    $this->setTypeHasRequiredOptions(false);
    $this->setHasOptions(false);
    $this->setRequiredOptions(false);

So when you make $product->save() it calls this method and set this attributes to false first.

For saving of product you should set options for product:

$product->setOptions($options)

For getting options for product you can write next code:

public function __construct(
     ...
     \Magento\Catalog\Api\ProductCustomOptionRepositoryInterface $productCustomOption
     ...
) {
    $this->productCustomOption = $productCustomOption;
}


public function getProductOptions($product)
{
     $options = $this->productCustomOption->getProductOptions($product)
}

P.S. Maybe this answer is not actual, however, maybe for someone will be useful.

0

My solution was to create a custom product type for my products that have custom product options. Then, in the product type model file add in a hasOptions($product) function to always return true.

This means I can create the product, save it with the repository methods, add options with addOption() and not have to resave the product hacking the product attribute has_options to 1 using some arcane method.

Clearly this will not help if you are not creating your own custom product types.

You can also set it so the product requires options and cannot therefore by added from the listing page.

Your Answer

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

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