Add/Update Attribute Option Values Programmatically in Magento


Adding/Updating the attribute option values programmatically in Magento can be tedious sometimes. Adding attribute options through custom codes is not big deal but updating the values for already added attribute options is tricky enough.
Problem: Lets understand this by an example. Suppose we have a product attribute ‘manufacturer’. It is of type select/dropdown. And we have few options added in it like Mac, Google, Android etc. Now at some point in our Magento application we want to update these options with Apple, Nexus, HTC etc without using the admin panel, then it is a problem.

Add/Update Attribute Option Values Programmatically in Magento

Solution: To update the option values programmatically, I came up with a simple solution which is as follows. For this, you need to find the ‘option_id’ of the attribute options in the ‘eav_attribute_option_value’ table.

Then create an option array and save it in the appropriate model.

Updating Attribute options

//Get the eav attribute model
$attr_model = Mage::getModel('catalog/resource_eav_attribute');

//Load the particular attribute by id
//Here 73 is the id of 'manufacturer' attribute

//Create an array to store the attribute data
$data = array();

//Create options array
$values = array(
 //15 is the option_id of the option in 'eav_attribute_option_value' table
 15 => array(
   0 => 'Apple' //0 is current store id, Apple is the new label for the option
 19 => array(
   0 => 'Nexus'
 12 => array(
   0 => 'HTC'

//Add the option values to the data
$data['option']['value'] = $values;

//Add data to our attribute model

//Save the updated model
try {
 $session = Mage::getSingleton('adminhtml/session');
  Mage::helper('catalog')->__('The product attribute has been saved.'));

  * Clear translation cache because attribute labels are stored in translation
} catch (Exception $e) {

This is all and you are done.

Adding new Attribute option

$arg_attribute = 'manufacturer';
$arg_value = 'value to be added';

$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();

$option['attribute_id'] = $attr_id;
$option['value']['any_option_name'][0] = $arg_value;

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

Leave a Reply

You must be logged in to post a comment.