Magento 1.9 Upgrade Script – How to Programmatically Add Attribute Option Values

magento-1.9upgrade-script

I want to programmatically add new product option values in a data upgade script of my module. How can I do this?

Best Answer

Add bellow code in your upgrade script file

<?php   
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$attributeCode = 'manufacturer';
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $attributeCode);

if ($attribute->getId() && $attribute->getFrontendInput()=='select') {
    $option['attribute_id'] = $attribute->getId();
    $option['value']        =  array('Red','Black', 'Yellow');
    $installer->addAttributeOption($option);
}

//OR
/*
if($attribute->getId() && $attribute->getFrontendInput()=='select') {
    $option['attribute_id'] = $attribute->getId();
    $option['value']['r'][0] = 'Red';
    $option['value']['b'][1] = 'Black';
    $option['value']['y'][2] = 'Yellow';
    $installer->addAttributeOption($option);
}*/

$installer->endSetup();

Check duplicate option value code:

<?php   
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$attributeCode = 'manufacturer';
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $attributeCode);

 if($attribute->getId() && $attribute->getFrontendInput()=='select') {
    $newOptions =  array('Red','Black', 'Yellow');
    $exitOptions =  array();
    $options = Mage::getModel('eav/entity_attribute_source_table')
                        ->setAttribute($attribute)
                        ->getAllOptions(false);
    foreach ($options as $option) {
        if (in_array($option['label'], $newOptions)) {
            array_push($exitOptions, $option['label']);
        }else {

        }
    }
    $insertOptions = array_diff($newOptions, $exitOptions);
    if(!empty($insertOptions)) {
        $option['attribute_id'] = $attribute->getId();
        $option['value']        =  $insertOptions;  
        $installer->addAttributeOption($option);
    }            
}

$installer->endSetup();
Related Topic