扩展magento的EAV属性模型


Extend Magento's EAV Attribute Model

我想在Magento的EAV属性模型中添加一个新属性。这可能吗?

我知道Magento允许您使用静态字段(在实体表上)扩展模型,但是我想向EAV属性表本身添加一个新字段(用于目录产品属性)。新属性将是一个新的设置,类似于"在类别列表中可见"。

要为产品属性添加一个新设置,您可以创建一个扩展,该扩展可以(1)将新列添加到catalog/eav_attribute表中,并且(2)使用观察者在属性编辑页面中为新设置添加一个字段。

(1)创建新的数据库字段(is_visible_in_category_list)

为扩展编写SQL脚本,并添加新列。我建议使用catalog/eav_attribute表,但是您也可以使用eav_attribute:

$installer = $this;
$installer->startSetup();
$table = $installer->getTable('catalog/eav_attribute');
$installer->getConnection()->addColumn(
    $table,
    'is_visible_in_category_list',
    "TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0'"
);
$installer->getConnection()->addKey(
    $table,
    'IDX_VISIBLE_IN_CATEGORY_LIST',
    'is_visible_in_category_list'
);
$installer->endSetup();

这里,我还添加了一个索引,以便更快地查询。

(2)将字段添加到编辑产品属性页面

在准备属性编辑表单时触发一个事件,因此让我们观察它:

<events>
    <adminhtml_catalog_product_attribute_edit_prepare_form>
        <observers>
            <is_visible_in_category_list_observer>
                <class>mymodule/observer</class>
                <method>addVisibleInCategoryListAttributeField</method>
            </is_visible_in_category_list_observer>
        </observers>
    </adminhtml_catalog_product_attribute_edit_prepare_form>
</events>

然后,在观察者中添加新的字段:

public function addVisibleInCategoryListAttributeField($observer)
{
    $fieldset = $observer->getForm()->getElement('base_fieldset');
    $attribute = $observer->getAttribute();
    $fieldset->addField('is_visible_in_category_list', 'select', array(
        'name'      => 'is_visible_in_category_list',
        'label'     => Mage::helper('mymodule')->__('Visible in Category List'),
        'title'     => Mage::helper('mymodule')->__('Visible in Category List'),
        'values'    => Mage::getModel('adminhtml/system_config_source_yesno')->toOptionArray(),
    ));
}

。将自动处理从编辑页面保存设置,因为表单中的字段名称与DB字段名称匹配。