magento2: Cannot create a numeric value attribute option using the REST API

Preconditions

Magento ver. 2.2.5 using the REST API.

Steps to reproduce

  1. Make a POST call to http://winninge.nextmp.net/rest/V1/products/attributes/<attribute_name>/options i.e., http://winninge.nextmp.net/rest/V1/products/attributes/Size/options setting the label and value to be a numeric string, for example { "option": { "label": "30", "value": "30", "sort_order": 0, "is_default": false, "store_labels": [{ "store_id": 0, "label": "30" }] } }

Expected result

  1. Attribute option to be created successfully with a 200 status code

Actual result

  1. The API responds with { "message": "Cannot save attribute %1", "parameters": ["size"] } and a 400 status code

This is happening when the attribute is a number, and a number alone. It also happens with floating point numbers, such as 6.5.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

To me it looks like this fix (https://github.com/magento/magento2/commit/3b9e96360e71b5d38167068b2b1a069ca97dc672) is trying to fix something that isn’t broken.

Proof

  • If you provide value for option (which is the option ID, incremental ID of the option, by the way) in the POST request, \Magento\Eav\Model\ResourceModel\Entity\Attribute::_updateAttributeOption will make just update query and no new option will be created.
  • After that \Magento\Eav\Model\ResourceModel\Entity\Attribute::_updateAttributeOptionValues will be called and it tries to insert values for the option to eav_attribute_option_value table and that insert obviously fails due to foreign key constraint failure, because there is no parent option row in eav_attribute_option table.

Conclusion

Option value (option ID) should not be provided in the request when creating new options. If this is acceptable, then this fix should be just reverted. Otherwise, fix should be changed so that resource model allows to create new option with given option ID and this ‘id_’ prefix fix is removed.

Note that this change “breaks” the way \Magento\Eav\Model\Entity\Attribute\OptionManagement::add could be used to e.g. update options’ store-specific labels, and now it always creates a new option in the database. This is because \Magento\Eav\Model\ResourceModel\Entity\Attribute::_updateAttributeOption checks if the $optionId is numeric, and does an insert if it’s not.

Created PRs for 2.2 and 2.3.

Hi @sidm , thank you for your report. We’ve acknowledged the issue and added to our backlog.