How to add attribute option in Magento programmatically using data upgrade/install script

How to add attribute option in Magento programmatically using data upgrade/install script

How to add attribute option in magento programmatically using data upgrade/install script

Here we are going to discuss on how Developers create custom attribute set. 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:


Thecan 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;
 * 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][0] = $attributeOptionToAdd;


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.

  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn
  • Youtube

leave a comment