Magento – Programmatically insert new attribute option

  • magento add attribute options programmatically
  • magento create attribute programmatically
  • magento add image label programatically
  • magento add attribute option programmatically
  • magento add attribute programmatically

Well, adding new attribute option from code seems to be easy at first. But in fact, it took me sometime to find out a solution. The main problem is that we need to get the option value of new option after saving. This is very important point when we are doing this from a Magento Import module

It was easy to find a function allow you to insert new attribute option. In order having option value, I tried to reload options list via Magento attribute model object but we meet Magento cache issue which you never get the new option saved with getAllOptions function.

Finally I found a solution which calling attribute source table directly to read all attribute options. Below are 2 utility function which is ready for you to use in your code

    public function addAttributeValue($arg_attribute, $arg_value)
    {
        $attribute_model        = Mage::getModel('eav/entity_attribute');

        $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
        $attribute              = $attribute_model->load($attribute_code);

        if(!$this->attributeValueExists($arg_attribute, $arg_value))
        {
            $value['option'] = array($arg_value,$arg_value);
            $result = array('value' => $value);
            $attribute->setData('option',$result);
            $attribute->save();
        }

		$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
        $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;
    }
	public function attributeValueExists($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;
    }

Comments Closed