Blog

Create Customer Attribute in Magento2

In Magento2, to create new custom attribute for customer you need your custom module.

If you have already any module installed in your magento then you can use UpgradeData.php file to create new customer attribute or if you don’t have any custom module then you can create new attribute by using InstallData.php file.

So first of all let’s see how to create new customer attribute with InstallData.php file.

Using InstallData.php

For that you need to create new custom module with registration.php file and etc/module.xml file. so let’s start…

1.) Create your namespace directory and module directory..

In this step, go to you Magento 2 root directory and navigate inside app/code directory and inside that directory create new directory and add your namespace and move inside it and create another subdirectory there with your module name.

2.) Add registration.php file.

In second step, you will need to create registration.php file here.

app/code/Thecoachsmb/CustomerAttribute/registration.php

Content for this file is..

<?php
/**
 * @package   Thecoachsmb\CustomerAttribute
 */
use \Magento\Framework\Component\ComponentRegistrar as Registrar;
Registrar::register( Registrar::MODULE, 'Thecoachsmb_CustomerAttribute', __DIR__ );

3.) Create module.xml file.

Create module.xml  file inside module’s etc/ directory here

app/code/Thecoachsmb/CustomerAttribute/etc/module.xml

Content for this file is..

<?xml version="1.0"?>
<!--
/**
 * @package   Thecoachsmb\CustomerAttribute
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:CustomerAttribute/etc/module.xsd">
    <module name="Thecoachsmb_CustomerAttribute" setup_version="1.0.0" />
</config>

4.) Create InstallData.php file.

Create Setup name directory inside your module and move into that directory and create InstallData.php file there..

app/code/Thecoachsmb/CustomerAttribute/Setup/InstallData.php

Content for this file is..

<?php

/**
 * @package   Thecoachsmb\CustomerAttribute
 */

namespace Thecoachsmb\CustomerAttribute\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Eav\Model\Config;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

class InstallData implements InstallDataInterface
{
    /**
     * @var Config
     */
    private $eavConfig;

    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;
    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    public function __construct(
        EavSetupFactory $eavSetupFactory,
        Config $eavConfig,
        AttributeSetFactory $attributeSetFactory
    ){
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){
        $customerEntity = $this->eavConfig->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            Customer::ENTITY,
            'customer_profile_link',
            [
                'type' => 'varchar',
                'label' => 'Customer Profile Link',
                'input' => 'text',
                'required' => false,
                'visible' => true,
                'user_defined' => true,
                'sort_order' => 50,
                'position' => 50,
                'system' => 0,
                'adminhtml_only' => 1,
            ]
        );

        $customAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'customer_profile_link');

        $customAttribute->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer']
        ]);

        $customAttribute->save();
    }
}

Here in above file, I added new attribute Customer profile link so we can use it in create account form and customer can put link and they can submit form.
Now, run below commands to activate new module and register it.

php bin/magento module:enable Thecoachsmb_CustomerAttribute
php bin/magento setup:upgrade

Above command will enable new module and register, also it’ll create new customer attribute. You can check your newly created attribute in eav_attribute table in your database.

Now, if you have any existing module already then you can follow below steps to create new customer attribute with the use of UpgradeData.php file..

2. Using UpgradeData.php

Create UpgradeData.php file inside Setup directory.

app/code/Thecoachsmb/CustomerAttribute/Setup/UpgradeData.php

Content for this file is..

<?php
/**
 * @package   Thecoachsmb\CustomerAttribute
 */

namespace Thecoachsmb\CustomerAttribute\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Eav\Model\Config;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

class UpgradeData implements UpgradeDataInterface
{
    private $eavSetupFactory;

    public function __construct(
        EavSetupFactory $eavSetupFactory,
        Config $eavConfig,
        AttributeSetFactory $attributeSetFactory
    ){
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context){
          $customerEntity = $this->eavConfig->getEntityType('customer');         
          $attributeSetId = $customerEntity->getDefaultAttributeSetId();         
          $attributeSet = $this->attributeSetFactory->create();         
          $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);        
         $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        if ($context->getVersion()
            && version_compare($context->getVersion(), '1.0.1') < 0
        ) {
            $eavSetup->addAttribute(
                Customer::ENTITY,
                'instagram_profile_link',
                [
                    'type' => 'varchar',
                    'label' => 'Instagram Profile link',
                    'input' => 'text',
                    'required' => false,
                    'visible' => true,
                    'user_defined' => true,
                    'sort_order' => 50,
                    'position' => 50,
                    'system' => 0,
                ]
            );
            $customAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'instagram_profile_link');
            $customAttribute->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer']
            ]);
        }
        $customAttribute->save();
    }
}

Now you have to change setup_version in your etc/module.xml file, we had 1.0.0 version previously, so we will change it from 1.0.0 to 1.0.1. So let’s do it.

app/code/Thecoachsmb/CustomerAttribute/etc/module.xml

Updated content after version change is liike below…

<?xml version="1.0"?>
<!--
/**
 * @package   Thecoachsmb\CustomerAttribute
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:CustomerAttribute/etc/module.xsd">
    <module name="Thecoachsmb_CustomerAttribute" setup_version="1.0.1" />
</config>

Now, you need to upgrade setup so run below command, and it will create your new attribute instagram_profile_link. You can set used_in_forms value based on your requirements. You can set following options in that array..

  • customer_account_create,
  • customer_account_edit,
  • checkout_register,
  • adminhtml_customer_address,
  • customer_address_edit,
  • customer_register_address

Depending upon in which forms you want to display this attribute, you can mention these name sin used_in_forms.
Then run the below command.

php bin/magento setup:upgrade

Leave a Reply

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

🚀 Let’s Connect on LinkedIn! 🚀

Want to level up your skills and knowledge? 🚀
Follow us on LinkedIn to get:
✅ Expert insights on business growth
✅ Daily tips to sharpen your skills
✅ Exclusive updates from The Coach SMB

Let's grow together!