Hi,
I ran into problems when trying to create new values for dropdown product attributes.
I created some product attribute with a select/dropdown input and type varchar. The source should be handled by Magento internally, I don’t need a custom source. So I left source empty. This correctly resulted in a source class of
Magento\Eav\Model\Entity\Attribute\Source\Table
Now how do I add selectable values to the dropdown (I need a proper eav_attribute_option_value
with an option_id
as it seems)?
I tried this code (which works if the $attributeValue
is a string containing alphas as 'brown'
, but I get the Exceptions mentioned below when I put in strings containing numbers eg. '40'
)
`
function createNewAttributeValue($attributeCode, $attributeValue)
{
$optionManagement = $this->objectManager->create('Magento\Catalog\Api\ProductAttributeOptionManagementInterface');
$option = $this->objectManager->create('Magento\Eav\Api\Data\AttributeOptionInterface');
$optionLabel = $this->objectManager->create('Magento\Eav\Api\Data\AttributeOptionLabelInterface');
$option->setLabel($attributeValue);
$option->setValue($attributeValue);
$option->setSortOrder(0);
$option->setIsDefault(0);
// $optionLabel->setLabel($attributeValue);
// $optionLabel->setStoreId(1); // TODO storeId dynamically?
// $option->setStoreLabels([$optionLabel]);
try {
if (!$optionManagement->add($attributeCode,$option)) {
throw new \Exception('Couldn\'t add option for attribute '.$attributeCode.': '.$attributeValue);
}
} catch (\Exception $e) {
throw new \Exception('Couldn\'t create option for attribute '.$attributeCode.': '.$attributeValue.' (['.get_class($e).']) '.$e->getMessage().')');
}
}
`
What happens when I put in “number strings” is that $optionManagement->add($attributeCode,$option)
throws an Cannot save attribute %s
from Magento\Eav\Model\Entity\Attribute\OptionManagement
, underneath that lies Magento\Eav\Model\ResourceModel\Entity\Attribute
extending Magento\Framework\Model\ResourceModel\Db\AbstractDb
with the following exception within function save()
:
[Zend_Db_Statement_Exception]) SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tablename
.eav_attribute_option_value
, CONSTRAINT EAV_ATTR_OPT_VAL_OPT_ID_EAV_ATTR_OPT_OPT_ID
FOREIGN KEY (option_id
) REFERENCES eav_attribute_option
(option_id
) ON DELETE ), query was: INSERT INTO eav_attribute_option_value
(option_id
, store_id
, value
) VALUES (?, ?, ?)))
Thats where I gave up… How do you add it properly?