Magento how to programmatically create category attribute


Step 1: Define Function


Magento 1


//File path: app/code/local/MageCheck/CategoryAttribute/etc/config.xml

<?xml version='1.0'?> <config> <modules> <MageCheck_CategoryAttribute> <version>0.0.1</version> </MageCheck_CategoryAttribute> </modules> <global> <resources> <customcatattrb_setup> <setup> <module>MageCheck_CategoryAttribute</module> <class>Mage_Eav_Model_Entity_Setup</class> </setup> <connection> <use>default_setup</use> </connection> </customcatattrb_setup> </resources> </global> </config>

Magento 2


<?php namespace MageCheck\Tutorial\Setup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\InstallDataInterface; class InstallData implements InstallDataInterface { private $eavSetupFactory; public function __construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory = $eavSetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $this->createCategoryAttribute($setup); $setup->endSetup(); } public function createCategoryAttribute($setup) { // ... } }

Step 2: Create Function


Magento 1


// File path: app/code/local/MageCheck/CategoryAttribute/sql/customcatattrb_setup/mysql4-install-0.0.1

<?php $installer = $this; $installer->startSetup(); $attribute = array( 'type' => 'text', 'label'=> 'Extension Attribute', 'input' => 'textarea', 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, 'visible' => true, 'required' => false, 'user_defined' => true, 'default' => '', 'group' => 'General Information' ); $installer->addAttribute('catalog_category', 'extension_attribute', $attribute); $installer->endSetup();

Magento 2


public function createCategoryAttribute($setup) { $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Category::ENTITY, 'extension_attribute', [ 'type' => 'text', 'label' => 'Extension Attribute', 'input' => 'textarea', 'required' => false, 'sort_order' => 4, 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, 'wysiwyg_enabled' => true, 'is_html_allowed_on_front' => true, 'group' => 'General Information', ] ); }