Skip to content

Instantly share code, notes, and snippets.

@ryaan-anthony
Last active April 6, 2018 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryaan-anthony/6287779 to your computer and use it in GitHub Desktop.
Save ryaan-anthony/6287779 to your computer and use it in GitHub Desktop.
<?php
class Ip_Global_Model_Backend_Newoption extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
/**
* Save EAV attribute option value if doesn't exist
*
* @param Varien_Object $object
* @return Ip_Global_Model_Backend_Newoption
*/
public function beforeSave($object)
{
$code = $this->getAttribute()->getAttributeCode();
if($object->getData($code)){
$option_id = $this->addAttributeValue($code, $object->getData($code));
$object->setData($code, $option_id);
}
return $this;
}
protected function getOptionId(Mage_Eav_Model_Entity_Attribute $attribute, $value)
{
/* @var Mage_Eav_Model_Entity_Attribute_Source_Table $attribute_options_model */
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_options_model->setAttribute($attribute);
return $attribute_options_model->getOptionId($value);
}
protected function addAttributeValue($code, $value)
{
/* @var Mage_Eav_Model_Entity_Attribute $attribute_model */
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_id = $attribute_model->getIdByCode('catalog_product', $code);
$attribute = $attribute_model->load($attribute_id);
if(!$option_id = $this->getOptionId($attribute, $value)){
/* @var Mage_Eav_Model_Entity_Setup $setup */
$setup = Mage::getModel('eav/entity_setup', 'core_setup');
$option['attribute_id'] = $attribute_id;
$option['value']['option_'.$attribute_id][0] = $value;
$setup->addAttributeOption($option);
$option_id = $this->getOptionId($attribute, $value);
}
return $option_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment