:::: MENU ::::

Custom variable programmatically in Magento

4.50 avg. rating (85% score) - 4 votes

This post continues the previous one about using Custom Variables in Magento.

This time we will create a new Custom Variable programmatically, which is useful if you develop a custom extension and need to save some data.

Some people ask me sometimes, why not use config data, which also provides a similar way of storing data for extensions. There are a main difference between both ways.

  • Config data are cached in Magento, so it is not recomended for data which changes often.
  • Custom variables are never cached, so they are always pulled from database, so we get the real value.

This slight differente is what you need to consider when adding some data from an extensión. If you don’t mind your values to be cached, then you should go for config data, as it’s more efficient. On the other hand, if your are storing some real-time data then you better go to Custom Variables.

Let’s see an example of how to create a new Custom Variable from code in Magento:

  $variable = Mage::getModel('core/variable')
                    ->setCode('variable-code')
                    ->setName('Variable Name')
                    ->setPlainValue(0)
                    ->save();

If you need to give a different value per store instead of globally:

  $variable = Mage::getModel('core/variable')
                    ->setCode('variable-code')
                    ->setName('Variable Name')
                    ->setStoreId($store)
                    ->setPlainValue(1)
                    ->save();

And then, you can also read the variable anywhere in the code, like this:

  $variable = Mage::getModel('core/variable')
                    ->loadByCode('variable-code');

Or if you want the value for a particular store:

  $variable = Mage::getModel('core/variable')
                    ->setStoreId($store)
                    ->loadByCode('variable-code');

You can store/obtain both the text or the html values of the variable:

echo Mage::getModel('core/variable')->loadByCode('variable-code') ->getValue('text');
echo Mage::getModel('core/variable')->loadByCode('variable-code') ->getValue('html');



One Comment

  • Responder Naveed Abbas |

    Hi,
    thanks for the article, this is really helpful.
    But I want to know is there is a way to update the html value of a variable programmatically?

    thanks
    Naveed

Hey! Qué opinas sobre el artículo?