How to create Customer attribute programmatically in magento 2?

Let’s we Create a simple Mobile number Customer attribute in magento 2. We need to create simple module for add new customer attribute in magento 2.

Create registration.php file to register our module. File Path, app/code/Rbj/CustomerAttribute/registration.php

Create module.xml file defined our module setup version to setup_module table. Create module.xml file defined our module setup version to setup_module table. File Path, app/code/Rbj/CustomerAttribute/etc/module.xml

We need to define our mobile customer attribute into extension_attributes.xml file. File path,app/code/Rbj/CustomerAttribute/etc/extension_attributes.xml 

Pass Classname inside for attribute in below xml as Magento\Customer\Api\Data\CustomerInterface because Its base Customer interface for create customer attribute in Magento 2. Set attribute code as your customer attribute code and define type as string.

 

For Create Customer attibute we need to define InstallData.php file to add entry in database of our attribute.
File Path, app/code/Rbj/CustomerAttribute/Setup/InstallData.php

Now Run the upgrade command to install our module.
You need to run command using SSh from the root of your Magento instance,

Now you can check your new mobile number attribute at admin panel.
Login with admin credential,
Go To, Customers -> All Customers -> Edit any Customer.

 

2 Replies to “How to create Customer attribute programmatically in magento 2?”

  1. Using extension_attribute, You can get above customer attribute easily in API call Using an extension_attributes array. extension_attribute is easily syncing with third-party application data sync using API.

Leave a Reply

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