In the following steps, we will create a small module that adds a customer attribute: loyaltynumber
Create a module Jeff_CustomerAttribute by creating files module.xml and registraction.php:
#app/code/Jeff/CustomerAttribute/etc/module.xml
Registration.php:
#app/code/Jeff/CustomerAttribute/Registration.php
Create a data installtion script: InstallData.php
#app/code/Jeff/CustomerAttribute/Setup/InstallData.php customerSetupFactory = $customerSetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $customerSetup =$this->customerSetupFactory->create(['setup'=>$setup]); $setup->startSetup(); $customerSetup->addAttribute('customer', 'loyaltynumber', [ 'label'=>'Loyaltynumber', 'type'=>'static', 'frontend_input'=>'text', 'required'=>false, 'visible'=>true, 'position'=>105, ]); $loyaltyAttribute = $customerSetup->getEavConfig()->getAttribute('customer', 'loyaltynumber'); $loyaltyAttribute->setData('used_in_forms', ['adminhtml_customer']); $loyaltyAttribute->save(); $setup->endSetup(); } }
Add the attribute to the backend, we have to create a ui_component XML file
#app/code/Jeff/CustomerAttribute/view/base/ui_component/customer_form.xml
To install the attribute in the database, run the command php bin/magento setup:upgrade in the Magento 2 root folder.
The required step is to add the attribute in the ui_component xml configuration. This configuration works like the layout XML files. When you look in the file app/code/Magento/Customer/view/adminhtml/layout/customer_index_edit.xml, you will set the following code that initializes the layout update of the ui_component:
In the backend, create a new customer. You will wee the Loyaltynumber attribute in the form like in the following screenshot: