Magento – insert new attribute option programmatically
As We know, its not easy at first to add new attribute options from code in Magento. it took time to find out solution. Actually the main problem is that we need to get the option value of new option after saving that’s essentail point when doing this from Magento.
We can find many functions that 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.
At last , I got a solution which calling attribute source table directly to read all attribute options. Below are 2 usefull functions which is ready for you to use in your code
Function 1:
- 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;
- }
Function 2:
- 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;
- }
Follow @phpzag

But wanna comment on few general things, The website design and style is perfect, the content is real fantastic : D.
I was more than happy to uncover this great site. I wanted to thank you for your time due to this wonderful read!! I definitely loved every part of it and I have you bookmarked to look at new information in your web site.