July 8th, 2009

Create a new Magento attribute and attribute group using the sql setup file

Category:Magento Development, Work Flow | Posted By Mai Erne at 11:06 AM

More than often, we need to create a new Magento attribute to extend some Magento functions, or even a new attribute group to serve our own module.  Here is how we do it using the sql setup file.

First, a few words about the sql setup file.

If this is the first time building the module or fresh installation, create a php file, say “mysql4-install-0.1.0.php”, in [company]/[module]/sql/[module]/[module]_setup/ folder, where the version 0.1.0 is defined the the config.xml file.

In case of module upgrade, try something like “mysql4-upgrade-0.1.0-0.2.0.php”, again, verify your upgrade version in the config.xml file.

Inside this file, first we need to initiate:

[codesyntax lang="php" lines="fancy"]

$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

[/codesyntax]

Then if you want to create a new attribute group:

[codesyntax lang="php" lines="fancy"]

$setup->addAttributeGroup('catalog_product', 'Default', 'Test Group', 1000);

[/codesyntax]

You can skip this line if you don’t want to create a new attribute group, here ‘catalog_product’ is used to retrieve the entityTypeId, you can use ‘sales_order’, ‘customer/customer’, ‘customer/address’ as well. ‘Default’ is the attributeSet Name. ‘Test Group’ is the Group name you want to create, you can just use the existing ones, such as ‘General’. 1000 is just the sort order, give it a big number so the new one will append to the end.

Next, adding a new attribute:

[codesyntax lang="php" lines="fancy"]

$setup->addAttribute('catalog_product', 'owner_id', array(
    'group' => 'General',
    'input' => 'text',
    'type' => 'text',
    'label' => 'Testing',
    'backend' => '',
    'visible' => 1,
    'required' => 0,
    'user_defined' => 1,
    'searchable' => 0,
    'filterable' => 0,
    'comparable' => 0,
    'visible_on_front' => 0,
    'visible_in_advanced_search' => 0,
    'is_html_allowed_on_front' => 0,
    'is_configurable' => 1,
    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

$installer->endSetup();

[/codesyntax]

The attribute added above will show up under the group/tab Special Attributes in product edit page.

No Comments for Current Post.

Comments are closed.