I am using below code to get the option Id with an attribute value/label in a custom extension.
/*
* Get attribute id based on option value
*/
protected function getAttributeOptionId($attributeCode, $label)
{
$productResource = $this->productFactory->create();
$attribute = $productResource->getAttribute($attributeCode);
if ($attribute->usesSource()) {
return $optionId = $attribute->getSource()->getOptionId($label);
}
}
This works fine in most cases. When I do a call with params color
and red
it works just fine.
But there is an issue when i call it with for instance attribute size
with value 20
. This only happens when there is an attribute label/value with id 20
. It just returns the first occurrence it finds (20 as a label or as an id).
I did some research and I found out why this is. Below code is the part which returns the id. The second part in the OR
condition $option['value'] == $value
causes my issue. It looks for a match in the label OR
value (which is the id). It just returns the first one found. I looked in the class there is no alternative method without the OR
condtion.
/**
* File: /vendor/magento/module-eav/Model/Entity/Attribute/Source/AbstractSource.php
* @param string $value
* @return null|string
*/
public function getOptionId($value)
{
foreach ($this->getAllOptions() as $option) {
if (strcasecmp($option['label'], $value) == 0 || $option['value'] == $value) {
return $option['value'];
}
}
return null;
}
My question is.
What is the best way to solve this? Is there an alternative way to get an id from a attribute label? Or should I rewrite the method? Or maybe extends the class and use a custom method? In any of these cases I would be glad to see an example or a place to start.