Tag Archives: value

Getting value of Attribute Option and adding a new Attribute Option in Magento

This, I find, is a hard one to come across. At least, trying to find a sensible solution that just spits out a numerical value which, more often than not, is all you want. Needing to get the value of an option from a multi-option/dropdown attribute. Try this:

public function getAttributeOptionValue($arg_attribute, $arg_value) {
    $attribute_model        = Mage::getModel('eav/entity_attribute');
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
 
    $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    $attribute              = $attribute_model->load($attribute_code);
 
    $attribute_table        = $attribute_options_model->setAttribute($attribute);
    $options                = $attribute_options_model->getAllOptions(false);
 
    foreach($options as $option) {
        if ($option['label'] == $arg_value) {
            return $option['value'];
        }
    }
 
    return false;
}

And use it as such:

$optionValue = $this->getAttributeOptionValue("size", "XL");

where “size” is the attribute name/ID in the database, and “XL” is the exact label belonging to the option you need to get. Likewise, if you need to add a new option to the attribute’s list, use this:

public function addAttributeOption($arg_attribute, $arg_value) {
    $attribute_model        = Mage::getModel('eav/entity_attribute');
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
 
    $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    $attribute              = $attribute_model->load($attribute_code);
 
    $attribute_table        = $attribute_options_model->setAttribute($attribute);
    $options                = $attribute_options_model->getAllOptions(false);
 
    $value['option'] = array($arg_value,$arg_value);
    $result = array('value' => $value);
    $attribute->setData('option',$result);
    $attribute->save();
 
    return $this->getAttributeOptionValue($arg_attribute, $arg_value);
}

and use as such:

$optionValue = $this->addAttributeOption("size", "XXL");

again, where “size” is the attribute name/ID, and “XXL” is the label of the new option required. It returns the value of the option it just added incase it’s needed. Bear in mind that this function doesn’t first check to see if the label already exists as an option, so you should probably use $this->getAttributeOption() first and only run $this->addAttributeOption() upon a false return.

It’s probably not the most efficient way of doing it, but if efficiency is what you really need, $options could be cached/saved so that the DB/model is only every queried once across both functions within the same model.