2

I have problems in adding values to an existing product attribute, using the API POST /products/attributes/:attribute_id/options. The corresponding GET API is working fine, as explained below.

I have defined a drop down product attribute in my store and I am trying to add values using Rest API.

I am able to retrieve the current values of the attribute with this GET call:

http://50.50.50.50/index.php/rest/V1/products/attributes/135/options

And I get, as expected, this result:

[
  {
    "label": " ",
    "value": ""
  },
  {
    "label": "Coffe",
    "value": "4"
  },
  {
    "label": "Tea",
    "value": "5"
  }
]

Then I try to add a new value with this POST call:

http://50.50.50.50/index.php/rest/V1/products/attributes/135/options

Passing the following value:

{
  "option": {
    "label": "Cappuccino",
    "value": "6"
  }
}

The response is: true

But if I repeat the first call, in order to get the new list of values, the new value is not added. I have tried to refresh all the caches and also restarted the server, but nothing have changed.

What I am doing wrong ?

Magento version is 2.1.5

Thanks, Nick.

2

2 Answers 2

0

I run into the same issue. After some debugging I found out that the values are used as an array index (e.g. debug the $object->toArray() in Magento\Framework\Model\ResourceModel\Db\AbstractDb::prepareDataForUpdate). At this place the information about the default value and sort order are already removed when using integers as value.

So easily do not use integers as values at this place. When using the backend to create/update an attribute manually, magento uses "option_1", "option_2" and so on for values.

Applied to your example, this would result in:

{
  "option": {
    "label": "Cappuccino",
    "value": "option_6"
  }
}

OT but related: Create an Attribute: When using POST /rest/V1/products/attributes to create an attribute having the options given, the options also won't be saved when using integers as values.

0

You need to something like this

{
  "option": {
    "label": "Cappuccino",
    "value": "option_6"
  }
}

In case you don't know the option number or you don't care just put option_x. in your example, it could be like this,

{
  "option": {
    "label": "Cappuccino",
    "value": "option_x"
  }
}

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.