I'm trying to programmatically add a custom option to a product, there are no errors being returned, but the custom option doesn't get added. I've tried a few methods to achieve this, without much luck.

Here's my code as it stands:

$product = $this->objectManager->get('Magento\Catalog\Model\Product')->load($productID);

$productOption = $this->objectManager->get('Magento\Catalog\Model\Product\Option');
    'title' => 'Text',
    'price' => '1.00',
    'max_characters' => '50',
    'price_type' => 'fixed',
    'sort_order' => '1'

Any ideas what I'm doing wrong?


I've now tried a different method:

$product = $this->objectManager->get('Magento\Catalog\Model\Product')->load($productID);
    'title' => 'Text',
    'type' => 'area',
    'is_require' => 1,
    'values' => [
            'title' => 'Text',
            'price' => '1.00',
            'price_type' => 'fixed',
            'max_characters' => '50'

But this gives me the following error:

[Magento\Framework\Validator\Exception] Invalid option value

However, I cannot figure out what's invalid.


You don't need to specify values for the option type you are trying to add. Please try example below.

/** @var \Magento\Catalog\Api\Data\ProductCustomOptionInterface $customOption */
$customOption = $this->objectManager->create('Magento\Catalog\Api\Data\ProductCustomOptionInterface');
$customOptions[] = $customOption;

Also, you can find a lot of examples on how to add products, attributes, options, etc in fixtures for integration tests. For instance, take a look in dev/tests/integration/testsuite/Magento/Catalog/_files

  • Got it working using your example. Do you know any examples for adding linked products for Bundle products? – Karl Jan 25 '16 at 17:03
  • Nice advice with tests! They can be much more up-to-date with current version of Magento (as there are a lot of updates these days). – Bartosz Kubicki May 31 '16 at 12:04
  • Hi Igor, I tried above but it is giving unable to handle request page. can you tell what should have gone wrong?? – aton1004 Jan 11 '17 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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