Magento how to programmatically create customer attribute


Step 1: Define Function


Magento 1


//File path: app/code/local/MageCheck/CustomerAttribute/etc/config.xml <?xml version='1.0'?> <config> <modules> <MageCheck_CustomerAttribute> <version>0.1.0</version> </MageCheck_CustomerAttribute> </modules> <global> <resources> <MageCheck_CustomerAttribute_setup> <setup> <module>MageCheck_CustomerAttribute</module> <class>Mage_Eav_Model_Entity_Setup</class> </setup> </MageCheck_CustomerAttribute_setup> </resources> </global> </config>

Magento 2


<?php namespace MageCheck\Tutorial\Setup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\UpgradeDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Eav\Model\Config; use Magento\Customer\Model\Customer; class UpgradeData implements UpgradeDataInterface { private $eavSetupFactory; private $eavConfig; public function __construct( EavSetupFactory $eavSetupFactory, Config $eavConfig ){ $this->eavSetupFactory = $eavSetupFactory; $this->eavConfig= $eavConfig; } public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); if (version_compare($context->getVersion(), '1.0.1', '<')) { $this->createCustomerAttribute($setup); } $setup->endSetup(); } public function createCustomerAttribute($setup) { // ... } }

Step 2: Create Function


Magento 1


// File path: app/code/local/MageCheck/CustomerAttribute/sql/MageCheck_CustomerAttribute_setup/mysql4-install-0.1

<?php $installer = $this; $installer->startSetup(); $customerEntityTypeId = $installer->getEntityTypeId('customer'); $atttributeCode = 'attribute_code'; $installer->removeAttribute($customerEntityTypeId, $atttributeCode); $installer->addAttribute('customer', $atttributeCode, array( 'type' => 'varchar', 'input' => 'text', 'label' => 'Attribute Name', 'global' => true, 'visible' => false, 'required' => false, 'user_defined' => true, 'visible_on_front' => false )); $usedInCustomerAddressForms = array( 'adminhtml_customer', 'customer_account_create' ); $attribute = Mage::getSingleton('eav/config')->getAttribute('customer', $attributeCode); $attribute->setData('used_in_forms', $usedInCustomerAddressForms); $attribute->save(); $this->endSetup();

Magento 2


public function createCustomerAttribute($setup) { $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Customer\Model\Customer::ENTITY, 'custom_extension', [ 'type' => 'varchar', 'label' => 'Customer Attribute', 'input' => 'text', 'required' => false, 'visible' => true, 'user_defined' => true, 'position' => 100, 'system' => false, ] ); $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'custom_extension'); $sampleAttribute->save(); }