Skip to content

Instantly share code, notes, and snippets.

@edannenberg
Last active October 12, 2016 23:03
Show Gist options
  • Save edannenberg/15c0eddfddad40eca32793708f67c331 to your computer and use it in GitHub Desktop.
Save edannenberg/15c0eddfddad40eca32793708f67c331 to your computer and use it in GitHub Desktop.
Mage_Eav_Model_Entity_Attribute_Source_Abstract::getOptionId() value/label collision

Had to investigate a weird bug in our product data, turns out to be a Magento core "feature" that can cause option id/label collisions when using getOptionId() of Mage_Eav_Model_Entity_Attribute_Source_Abstract.

Truncated getAllOptions() array for a common size attribute:

Array
(
  [232] => Array
          (
              [value] => 104
              [label] => 44
          )
  [331] => Array
          (
              [value] => 405
              [label] => 104
          )
)

Mage_Eav_Model_Entity_Attribute_Source_Abstract::getOptionId() implementation in 1.9.2.4:

    public function getOptionId($value)
    {
        foreach ($this->getAllOptions() as $option) {
            if (strcasecmp($option['label'], $value)==0 || $option['value'] == $value) {
                return $option['value'];
            }
        }
        return null;
    }

Fetch option id for labels 44 and 104:

$a = Mage::getModel('eav/entity_attribute')->load(<attribute_id>);
$optionId = $a->getSource()->getOptionId("44"); 
$optionId = $a->getSource()->getOptionId("104");

Both calls will return 104 as id for the option label, should be 405 for the second call. Patch below, in theory this might break existing code, but probably safe to apply in practice.

diff -rupN magento-lts/app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Abstract.php magento-lts-patched/app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Abstract.php
--- magento-lts/app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Abstract.php 2016-10-09 23:12:43.587187800 +0200
+++ magento-lts-patched/app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Abstract.php 2016-10-09 23:16:44.357177946 +0200
@@ -95,7 +95,7 @@ abstract class Mage_Eav_Model_Entity_Att
public function getOptionId($value)
{
foreach ($this->getAllOptions() as $option) {
- if (strcasecmp($option['label'], $value)==0 || $option['value'] == $value) {
+ if (strcasecmp($option['label'], $value)==0) {
return $option['value'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment