How To Add Customer Attribute In Magento 2
Many of us are facing problems in adding custom attributes to customer profile in Magento 2. Here is how to add a custom field in Magento 2. Thanks to sashas extension for providing easy solution on adding a custom field.
There are many ways to add custom field for customers in Magento 2. Today we will focus on extension for Magento 2 which adds attribute to customer edit page at admin.
To begin with you will need Magento 2 installed with demo data. For more information you can see the Magento 2 installation guide.
Our step by step instruction allow you to create a successful attribute of Customer in admin panel.
Read Complete Tutorial Here: http://arpatech.com/blog/add-custome...e-magento-2-x/
How To Add Customer Attribute In Magento 2?
The main part is DataInstall::install method
Code:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** @var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, '{attributeCode}', [
'type' => 'varchar',
'label' => '{attributeLabel}',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
//add attribute to attribute set
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'magento_username')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}