Select attributes with numeric labels
-
29-09-2020 - |
Frage
I believe this is a core Magento bug, but thought I'd come here to ask for some suggestions anyway.
I've got an attribute, let's call it colour_code
. It's a select attribute (backend is int
) and it's configurable. It's identical in eav_attribute
and catalog_eav_attribute
configuration to the default size
attribute by the way.
I've been fixturing products with this attribute in some unit tests, and noticed that if my attribute value (label) is numeric, Magento can get confused with the value and the label, for example:
# Mage_Eav_Model_Entity_Attribute_Source_Abstract::getAllOptions()
Array
(
Array
(
[value] => 902
[label] => 143
)
Array
(
[value] => 386
[label] => 902
)
Array
(
[value] => 316
[label] => A01
)
)
Using the above as a very small example of the result of getAllOptions
for the attribute's source ($attribute->getSource()->getAllOptions()
), I check the
fixtured products values like so:
// Product fixture has colour_code: A01
$product->getColourCode(); // 316 <--- the option_id
// Product fixture has colour_code: 902
$product->getColourCode(); // 902 <--- the VALUE
The problem is when using colour code 902 it returns 902, instead of the option ID. I don't particularly like the fact that Magento returns the option ID, but understand why. That's fine, as long as it's consistent - in this case it's not at all.
Using 902
as the $value
, I've drilled this down to the logic in Mage_Eav_Model_Entity_Attribute_Source_Abstract::getOptionId
line 98, where strcasecmp($option['label'], $value)==0
returns false, then $option['value'] == $value
returns true on the first entry in that example array (value = 902, label = 143). In this case, the method returns $option['value']
, which is 902. It doesn't get a chance to look at the valid option (option_id 386).
public function getOptionId($value)
{
foreach ($this->getAllOptions() as $option) {
if (strcasecmp($option['label'], $value)==0 || $option['value'] == $value) {
^--- this causes the problem!
return $option['value'];
}
}
return null;
}
What can I do about this?
Lösung
For multi-select attributes, this is expected behaviour.
If you want the frontend/text value of the attribute you can use Mage_Catalog_Model_Product::getAttributeText
with the attribute code:
$product->getAttributeText('colour_code'); // A01