How to add attribute option in magento programatically using data upgrade/install script
This post will be helpful if you are not completely new to magento. In some cases we need to add some new attribute options pragmatically. This will avoid manual effort of doing the same thing in all environments and the such changes will be updated on each environment immediately after your code deployed.
Step1: Make sure your module's config.xml looks like the below:
0.1.0 Egits_Catalog Mage_Eav_Model_Entity_Setup
can be your own custom one or the same as above. If you are using a custom class, make sure it extends the class Mage_Eav_Model_Entity_Setup
Step 2: Create your data install/upgrade script
If you already created a magento module and assigned a version number to your magento moduleCreate app/code/local/NameSpace_Module/data/data-upgrade-0.1.0-0.2.0.php - here 0.1.0 is your old version number and 0.2.0 is the new one. Make sure you update the version number in config.xml
If you are creating a new module for this purpose, a data install script will do. To achieve this, create app/code/local/NameSpace_Module/data/data-install-0.1.0.php
Once you created your data upgrade/install script add below code to it
$installer = $this; $installer->startSetup(); /** * Adding new option to the attribute */ $attributeCode = 'attribute_code_here'; $attributeOptionToAdd = 'New Option'; $attributeModel = Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product', $attributeCode); $attributeId = $attributeModel->getAttributeId(); $option['attribute_id'] = $attributeId; $option['value'][$attributeOptionToAdd] = $attributeOptionToAdd; $installer->addAttributeOption($option);
Step 3: Update Module Version number
Update the version number in your config.xml. This is the important part to run the data install/upgrade script
1. If yours is a new module, then update it with a version number, Mine is "0.1.0"
2. If the module ia already existing then increase the version by 1 depending on the changes in that version
In both cases, you should use your version number in install/upgrade script naming. In first case you can use "data-install-0.1.0.php" but in second case you should use "data-upgrade-0.1.0-0.2.0.php" which indicates your module is updating from an old version(0.1.0) to a new version(0.2.0)
Step4: Clear Cache & run front end
Now you should clear magento cache directory and access your store frontend
That's it! you are all done. Check your attribute now.