When writing Magento Modules (or updating them), you’ll often find yourself in the situation where some of the functionality depends on the presence of a specific product attribute.
As you know, you can use an installer script to create product attributes programmatically, just like you can create static blocks programmatically. Since I encounter this situation often myself, I’ll show you how I do this in an install- or upgrade script.
The code
Here is the code that I use: you can edit it and use it in your installer scripts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php // This installer scripts adds a product attribute to Magento programmatically. // Set data: $attributeName = 'Custom Attribute'; // Name of the attribute $attributeCode = 'custom_attribute'; // Code of the attribute $attributeGroup = 'General'; // Group to add the attribute to $attributeSetIds = array(4); // Array with attribute set ID's to add this attribute to. (ID:4 is the Default Attribute Set) // Configuration: $data = array( 'type' => 'varchar', // Attribute type 'input' => 'text', // Input type 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, // Attribute scope 'required' => false, // Is this attribute required? 'user_defined' => false, 'searchable' => false, 'filterable' => false, 'comparable' => false, 'visible_on_front' => false, 'unique' => false, 'used_in_product_listing' => true, // Filled from above: 'label' => $attributeName ); // Create attribute: // We create a new installer class here so we can also use this snippet in a non-EAV setup script. $installer = Mage::getResourceModel('catalog/setup', 'catalog_setup'); $installer->startSetup(); $installer->addAttribute('catalog_product', $attributeCode, $data); // Add the attribute to the proper sets/groups: foreach($attributeSetIds as $attributeSetId) { $installer->addAttributeToGroup('catalog_product', $attributeSetId, $attributeGroup, $attributeCode); } // Done: $installer->endSetup(); |
Visitors give this article an average rating of 3.2 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Very good code…100% working
Hi Geil, I have a single vendor store and would like to convert it to multivendor by programming and not using extensions. How can I do this? Could you please guide me?
Very Nice code ..Worked on first run..