I am creating a new attribute (mobile) for the Customer Entity. The attribute should be of type 'static' since this one is a required field and for easy retrieval.
I came to know that it requires 2 steps:
- Create a column in the customer_entity table.
- Add an attribute to the customer entity with Patch.
Below is my code:
- Creating column in customer_entity table.
db_schema.xml
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="customer_entity">
<column xsi:type="varchar" name="mobile" comment="Customer Mobile Number" nullable="false"/>
</table>
</schema>
Generated scheme whitelist db_schema_whitelist.json
:
{
"customer_entity": {
"column": {
"mobile": true
}
}
}
- Created a Data Patch for adding a new attribute in the
eav_attribute
table,AddMobileAttributePatch.php
:
public function apply()
{
$this->moduleDataSetup->startSetup();
$customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'static',
'label' => 'Mobile Number',
'input' => 'text',
'required' => true,
'unique' => true,
'visible' => true,
'user_defined' => true,
'position' => 999,
'system' => 0,
]
);
$attribute = $customerSetup->getEavConfig()
->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'mobile')
->addData([
'used_in_forms' => [
'adminhtml_customer',
'checkout_register',
'customer_account_create',
'customer_account_edit'
],
]);
$attribute->save();
$this->moduleDataSetup->endSetup();
}
Now the column is created in the customer_entity
table and a new attribute is available in the eav_attribute
table. The field is also available in the Admin Customer Edit Form.
The problem is when I enter some data into the mobile
field and hit save, it returns the error " Mobile Number" is a required value.
. This error is from the server-side and Js validation is working fine.