🧩 Magento 2 Custom User Attributes – Add Personalized Fields to Registration
Want to capture more than just name and email? Magento 2 lets you add custom user attributes (like Date of Birth, Gender, Company ID) to customer registration or account pages with ease.
🎯 Where Are User Attributes Stored?
Customer attributes are part of the EAV (Entity-Attribute-Value) model in Magento. You can create your own attributes using setup scripts or declarative schema.
🛠 Create a Custom Customer Attribute
Here’s how to add a custom customer attribute called company_id
.
// Add a custom attribute to the customer entity $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]); $customerSetup->addAttribute( \Magento\Customer\Model\Customer::ENTITY, 'company_id', [ 'type' => 'varchar', 'label' => 'Company ID', 'input' => 'text', 'required' => false, 'visible' => true, 'user_defined' => true, 'position' => 200, 'system' => 0, ] ); // Add attribute to forms $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'company_id'); $attribute->setData('used_in_forms', ['adminhtml_customer', 'customer_account_create', 'customer_account_edit']); $attribute->save();
🧪 Display Custom Attribute on Frontend
To show your new attribute on the registration or account edit page, ensure it’s added in:
view/frontend/templates/form/register.phtml
Example:
<div class="field"> <label for="company_id">Company ID</label> <input type="text" name="company_id" id="company_id" /> </div>
🔄 Save & Load Attribute Data
Magento will automatically save and load the value once it’s registered in the forms. You can also retrieve it programmatically:
// Get the custom attribute value $customer = $this->customerRepository->getById(123); $companyId = $customer->getCustomAttribute('company_id')->getValue();
✅ Summary
- Create custom user attributes using
customerSetup->addAttribute()
- Assign them to forms like registration, account edit, or admin
- Display them via template overrides
- Fetch their values using the
getCustomAttribute()
method
Custom user attributes help you personalize the customer experience and collect more business-relevant data. Perfect for B2B, advanced analytics, and targeted features!