How to add customer attributes in Magento 2 programmatically and that attribute display in a grid.
Magento 2 Custom Customer Attribute is useful when you want to add a custom field in customer address form and customer account page. After that, You can also get custom attribute value in customer objects.
Creating customer custom attributes supports you in smartly understanding the customer. Some examples of custom customer attributes are visitors’ mobile numbers, interests/hobbies, etc. Depending on your requirement, you may need to add more fields.
Introduce several ways to add an extra tab to order view, Taken Dolphin as Package name and PhoneNumber as Modulename for simplicity. code snippets are under a module named Dolphin_PhoneNumber.
Before creating the customer attribute, we need to create a new module We already have a blog on “how to create a basic module in Magento 2“. We need to create module.xml and registration.php file. You can create module.xml and registration.php from this tutorial.
You also Like To use This: Customer Attributes Extension for Magento 2
Create Class (DataPatch File)
Magento introduces a new way to modify data in Magento 2 database: Data / Schema Patches (Magento Documentation). Implement a data patch to add a customer’s attribute to the database.
Create an “AddCustomerPhoneNumber.php” file in the app/code/Dolphin/PhoneNumber/Setup/Patch/Data folder with the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | <?php namespace Dolphin\PhoneNumber\Setup\Patch\Data; use Magento\Customer\Model\Customer; use Magento\Customer\Setup\CustomerSetup; use Magento\Customer\Setup\CustomerSetupFactory; use Magento\Eav\Model\Entity\Attribute\Set; use Magento\Eav\Model\Entity\Attribute\SetFactory; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; use Magento\Framework\Setup\Patch\PatchRevertableInterface; class AddCustomerPhoneNumber implements DataPatchInterface, PatchRevertableInterface { /** * @var ModuleDataSetupInterface */ private $moduleDataSetup; /** * @var CustomerSetup */ private $customerSetupFactory; /** * @var SetFactory */ private $attributeSetFactory; /** * Constructor * * @param ModuleDataSetupInterface $moduleDataSetup * @param CustomerSetupFactory $customerSetupFactory * @param SetFactory $attributeSetFactory */ public function __construct( ModuleDataSetupInterface $moduleDataSetup, CustomerSetupFactory $customerSetupFactory, SetFactory $attributeSetFactory ) { $this->moduleDataSetup = $moduleDataSetup; $this->customerSetupFactory = $customerSetupFactory; $this->attributeSetFactory = $attributeSetFactory; } /** * {@inheritdoc} */ public function apply() { $this->moduleDataSetup->getConnection()->startSetup(); /** @var CustomerSetup $customerSetup */ $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]); $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY); $attributeSetId = $customerEntity->getDefaultAttributeSetId(); /** @var $attributeSet Set */ $attributeSet = $this->attributeSetFactory->create(); $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId); $customerSetup->addAttribute( Customer::ENTITY, 'phone_number', [ 'label' => 'Phone Number', 'input' => 'text', 'type' => 'varchar', 'source' => '', 'required' => false, 'position' => 333, 'visible' => true, 'system' => false, 'is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false, 'backend' => '' ] ); $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'phone_number'); $attribute->addData([ 'used_in_forms' => [ 'adminhtml_customer', 'customer_account_create', 'customer_account_edit' ] ]); $attribute->addData([ 'attribute_set_id' => $attributeSetId, 'attribute_group_id' => $attributeGroupId ]); $attribute->save(); $this->moduleDataSetup->getConnection()->endSetup(); } public function revert() { $this->moduleDataSetup->getConnection()->startSetup(); /** @var CustomerSetup $customerSetup */ $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]); $customerSetup->removeAttribute(\Magento\Customer\Model\Customer::ENTITY, 'phone_number'); $this->moduleDataSetup->getConnection()->endSetup(); } /** * {@inheritdoc} */ public function getAliases() { return []; } /** * {@inheritdoc} */ public static function getDependencies() { return [ ]; } } |
After , run below command to install the module:
Result:
Now Add This Attribute in Admin Grid in Magento 2
Step:1 Create Listing UI Component
Create a “customer_listing.xml” file in the app/code/Dolphin/PhoneNumber/view/adminhtml/ui_component folder with the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?xml version="1.0" encoding="UTF-8"?> <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> <listingToolbar name="listing_top"/> <columns name="customer_columns" class="Magento\Customer\Ui\Component\Listing\Columns"> <column name="phone_number" class="Dolphin\PhoneNumber\Ui\Component\Listing\Column\PhoneNumber"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="filter" xsi:type="string">text</item> <item name="editor" xsi:type="string">text</item> <item name="label" xsi:type="string" translate="true">Phone Number</item> <item name="sortOrder" xsi:type="number">40</item> </item> </argument> </column> </columns> </listing> |
Step:2 Create Class
Create a “PhoneNumber.php” file in the app/code/Dolphin/PhoneNumber/Ui/Component/Listing/Column folder with the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | <?php namespace Dolphin\PhoneNumber\Ui\Component\Listing\Column; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; class PhoneNumber extends Column { /** * * @param ContextInterface $context * @param UiComponentFactory $uiComponentFactory * @param array $components * @param array $data */ public function __construct( ContextInterface $context, UiComponentFactory $uiComponentFactory, array $components = [], array $data = [] ) { parent::__construct($context, $uiComponentFactory, $components, $data); } /** * Prepare Data Source * * @param array $dataSource * @return array */ public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customer = $objectManager->create('Magento\Customer\Model\Customer')->load($item['entity_id']); $item[$this->getData('name')] = $customer->getPhoneNumber(); } } return $dataSource; } } ?> |
Step:3 Create extension_attributes
Create a “extension_attributes.xml” file in the app/code/Dolphin/PhoneNumber/etc folder with the following code.
1 2 3 4 5 6 7 | <?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd"> <extension_attributes for="Magento\Customer\Api\Data\CustomerInterface"> <attribute code="customer_phone_number" type="string"/> </extension_attributes> </config> |
-
- extension attributes: Check the interface for the methods
getExtensionAttributes()
andsetExtensionAttributes()
to determine if they are available for the entity
- extension attributes: Check the interface for the methods
Result:
I Hope, This instruction will be helpful for you.
If you have any difficulties regarding this blog, do consider them posting in the Comments section below!
I’m here to help.
Thank you!