Home » Php » php – Extend Magento's EAV Attribute Model

php – Extend Magento's EAV Attribute Model

Posted by: admin July 12, 2020 Leave a comment

Questions:

I would like to add a new attribute to Magento’s EAV attribute model. Is this possible?

I know that Magento lets you extend models using static fields (which are on the entity table), but I would like to add a new field to the EAV attribute table itself (for catalog product attributes). The new attribute will be a new setting, similar to “Visible in Category List”.

How to&Answers:

To add a new setting for product attributes, you can create an extension that (1) adds the new column to the catalog/eav_attribute table, and (2) puts in a field for the new setting in the attribute edit page using an observer.

(1) Create your new DB field (is_visible_in_category_list)

Make an SQL script for your extension, and add the new column. I would recommend using the catalog/eav_attribute table, but you could probably use eav_attribute as well:

$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();

Here, I also added an index for faster querying.

(2) Add the field to the edit product attribute page

An event is fired when preparing the attribute edit form, so let’s observe it:

<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>

Then, add the new field in the observer:

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(),
    ));
}

That’s all. Saving the setting from the edit page is automatically handled because the field name in the form matches the DB field name.