Adding Multi-select Attributes using an Installer in Magento

piaoling  2011-10-14 10:50:30

I had to do a modification for a Magento install that required the use of adding a multi-select attribute. Most other people would just add the attribute by hand and forget about it, but I’m one for making the upgrade process easy. However, the Magento developers don’t seem to want you to know about it (or anything else for that matter, given the lack of documentation!!). Anyway, I eventually stumbled across a small snippet of code, and after a bit of tweaking to figure out where all the parameters went, the installer worked. Easy upgrading :)

// File: app/code/local/MyCompany/Catalog/sql/mysql4-install-0.1.php
// OR
// File: app/code/local/MyCompany/Catalog/sql/mysql4-upgrade-0.1-0.2.php
 
$installer = $this;
$installer->startSetup();
 
$installer->addAttribute('catalog_product', 'attr_id',array(
			 'label'             => 'Frontend Name',
			 'type'              => 'varchar',
			 'input'             => 'multiselect',
			 'backend'           => 'eav/entity_attribute_backend_array',
			 'frontend'          => '',
			 'source'            => '',
			 'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
			 'visible'           => true,
			 'required'          => false,
			 'user_defined'      => false,
			 'searchable'        => false,
			 'filterable'        => false,
			 'comparable'        => false,
			 'option'            => array (
			 	'value' => array('optionone' => array('First Option'),
			 			 'optiontwo' => array('Second Option'),
			 			 'optionthree' => array('Third Option'),
			 			 )
			 			),
			 'visible_on_front'  => false,
			 'visible_in_advanced_search' => false,
			 'unique'            => false
));
 
$installer->endSetup();

Of course, ‘addAttribute’ isn’t a method of $installer (or $this if you’re running a standard Mysql4 setup). So you have to extend a different setup with addAttribute defined. I found this one works well:

// File: app/code/local/MyCompany/Catalog/Model/Mysql4/Setup.php
 
class MyCompany_Catalog_Model_Mysql4_Setup extends Mage_Sales_Model_Mysql4_Setup {}

One thing to note with this however, is that the attribute will end up as a System attribute, and applied to every attribute set on the system. I’m currently working on a way around this, and will edit this post when I have something more to share. :)

类别 :  magento(258)  |  浏览(6089)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: