Last active
April 6, 2018 13:58
-
-
Save ryaan-anthony/6287779 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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