·

photo credit: See-ming Lee ??? SML via photopin cc

How to add custom attributes to a category in Magento

Sometimes you have the need to add some custom attributes to a category in Magento. This is actually very simple to implement. In this article I’ll assume that you already know how to build a Magento module. Therefore I will not explain the whole ‘how to create a Magento module’-part, since there are already enough articles out there that cover that topic. Instead, I’ll just show you the most basic way on how to add custom attributes to a category in Magento.

Configuration

Make sure your module has a setup script, if you don’t know how to do this, here’s a simple layout. The following code should be placed inside your <global> -block in your config.xml :

The above script simple makes sure your module will be able to execute a setup-script. Which we will place in our module. The path and filename to this file must be sql/mymodule_setup/mysql4-install-0.0.1.php  (assumimg your modules’ namespace is mymodule  and your version is 0.0.1). The following code should be placed inside this script:

That’s it! Now you’ll have an extra tab on your ‘edit category’-page which allows you to save an extra attribute. This is the most basic example.

Going beyond basic

You might have noticed 2 things in this example: input  and type :

  • Input determines the type of input element to show. This can be a lot of things, like text, textarea, date, file, etc. To get an idea of what’s possible, you should check out the /lib/Varien/Data/Form/Element -folder.
  • Type determines the EAV-table in which the value of this input element is stored. This can be datetime, decimal, int, text or varchar.

Using select box dropdowns

At some point you might want to be able to have a dropdown with options when editing a category. Again, this is really easy to do by using a select -inputtype and a source model:

Notice that we changed ‘input’ to ‘select’, ‘type’ to ‘int’ and added an extra item: ‘source’. What ‘source’ does, is load a Magento Model and invoke the getAllOptions() -method on it. So, needless to say, we need to add a new model in Model/Source/Custom.php  with the following code:

This source model returns a simple array where the key is the value that is stored in the database, and the value the text that is displayed in the dropdown.
So that’s it! Now you are able to add custom attributes to categories.

Visitors give this article an average rating of 3.9 out of 5.

How would you rate this article?

One thought on “How to add custom attributes to a category in Magento”

  1. neha says:

    How to use more than one attribute

Leave a Reply