Magento how to programmatically create product attribute


Step 1: Define Function


Magento 1


<?php class MageCheck_Tutorial_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this-> createProductAttribute(); } public function createProductAttribute() { // ... } }

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->creatingProductAttribute($setup); $setup->endSetup(); } public function creatingProductAttribute() { // ... } }

Step 2: Create Function


Magento 1


public function createProductAttribute() { $installer = new Mage_Eav_Model_Entity_Setup('core_setup'); $installer->startSetup(); $installer->addAttribute('catalog_product', 'productattribute_example', array( 'group' => 'General', 'label' => 'Attribute Example', 'input' => 'text', 'type' => 'varchar', 'required' => 0, 'visible_on_front' => 1, 'filterable' => 0, 'searchable' => 0, 'comparable' => 0, 'user_defined' => 1, 'is_configurable' => 0, 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, 'note' => '', )); $installer->endSetup(); }

Magento 2


public function creatingProductAttribute() { $installer = $this->_installer; $attribute = $this->_attribute; $attributeRepository = $this->_attributeRepository; $indexAdmin = 0; $indexEnglish = 12; $attributes_meta = array( 'Finish' => array( 'type' => 'swatch_visual', 'visible' => true, 'options' => array( 'Option 1', 'Option 2', ), ), ); foreach ($attributes_meta as $attribute_label => $attribute_meta) { $attribute_type = empty($attribute_meta['type']) ? 'text' : $attribute_meta['type']; $attribute_data = array( 'entity_type_id' => $installer->getEntityTypeId('catalog_product'), 'attribute_code' => 'extension_attribute', 'backend_type' => 'int', 'frontend_input' => 'swatch_' === substr($attribute_type, 0, strlen('swatch_')) ? 'select' : $attribute_type, 'frontend_label' => [$attribute_label], 'is_required' => 0, 'is_user_defined' => 1, 'is_unique' => 0, 'is_global' => 1, 'is_visible' => 1, 'is_searchable' => 0, 'is_filterable' => 0, 'is_comparable' => 0, 'is_visible_on_front' => 0, 'is_visible_in_advanced_search' => 1, 'is_required_in_admin_store' => 0, 'is_used_in_grid' => 1, 'is_visible_in_grid' => 1, 'is_filterable_in_grid' => 1, ); $attribute->setData($attribute_data); $attribute->save(); $installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId()); } }