How to Add New Customer Attribute in Magento 2

In Magento 2 enterprise edition, we have an option on the admin side to add new customer attribute. But in Magento 2 community edition, there is no option on the admin side. But we can able to create a customer attribute by using an installable script. This blog will help you to create new customer attribute programmatically.

Step 1: Module Registration

Create a new custom module based on the Magento 2 structure in the below file path,

File Path: app/code/BlogTreat/CustomerAttribute/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'BlogTreat_CustomerAttribute',
    __DIR__
);

Step 2: Module Configuration

Create a module.xml file in the below file path to define new Magento 2 extension

File Path: app/code/BlogTreat/CustomerAttribute/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="BlogTreat_CustomerAttribute" setup_version="1.0.0">
    </module>
</config>

Step 3: Create a Setup File

Create a setup file InstallData.php in the below file path,

File Path: app/code/BlogTreat/CustomerAttribute/Setup/InstallData.php

<?php
namespace BlogTreat\CustomerAttribute\Setup;
 
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
  
/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
     
    /**
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;
     
    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;
     
    /**
     * @param CustomerSetupFactory $customerSetupFactory
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }
  
     
    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, 'new_custom_attribute', [
            'type' => 'varchar',
            'label' => 'Custom Attribute',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'position' => 999,
            'system' => 0,
        ]);
         
        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'new_custom_attribute')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer', 'customer_account_create', 'customer_account_edit'],//you can use other forms also
        ]);
         
        $attribute->save();
    }
}

After completing the above steps run the below SSH command in your Magento 2 installed root directory,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check whether the extension has been successfully installed in Magento 2 admin.

Once the extension has been installed you will be able to view the customer attribute in admin side as shown in the screenshot below,

How to Add New Customer Attribute in Magento 2

Note:

By default, the newly created customer attribute will not be displayed in the frontend. We need to customize the code to display the newly created customer attribute in the frontend.

Copy vendor/magento/module-customer/view/frontend/templates/form/edit.phtml to app/design/frontend/[Vendor]/[theme]/Magento_Customer/templates/form/edit.phtml and add the following code to display the newly created customer attribute in the account edit page,

<div class="field custom_attribute">
    <label class="label" for="new_custom_attribute"><span><?php /* @escapeNotVerified */ echo __('Custom Attribute') ?></span></label>
    <div class="control">
        <input type="text" id="new_custom_attribute" name="new_custom_attribute" value="<?php echo $block->escapeHtml($block->getCustomer()->getCustomAttribute('new_custom_attribute')->getValue()) ?>" title="<?php /* @escapeNotVerified */ echo __('Custom Attribute') ?>" class="input-text" autocomplete="off" />
    </div>
</div>

Hope this helps.

One Comment on “How to Add New Customer Attribute in Magento 2”

  1. Thanks for the article.
    I have a query though, How can i show a select type attribute on account edit page?

Leave a Reply

Your email address will not be published. Required fields are marked *