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
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.
<?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:
Read this: Create Sales Order Programmatically in Magento 2
Now Add This Attribute in Admin Grid in Magento 2
Create a “customer_listing.xml” file in the app/code/Dolphin/PhoneNumber/view/adminhtml/ui_component folder with the following code.
<?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>
Create a “PhoneNumber.php” file in the app/code/Dolphin/PhoneNumber/Ui/Component/Listing/Column folder with the following code.
<?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.
<?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>
getExtensionAttributes()
and setExtensionAttributes()
to determine if they are available for the entityResult:
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!