How to Create Customer Attribute in Magento 2

How to Create Customer Attribute in Magento 2

by Van Nguyen

Are you finding how to create customer attribute in Magento 2 programmatically? The article is your answer. Follow our guide below, we use a simple module demo coding for this lesson, so for the first, you need to read the tutorial here to create a simple module as BSS_HelloWorld. And now are the instructions to add customer attribute Magento 2 in 2 ways: using code and Magento extensions.

Step-by-Step to Create Customer Attribute in Magento 2 Programmatically

Step 1: Create a setup file InstallData.php

Firstly, we need to create the InstallData.php file located at file: app/code/BSS/HelloWorld/Setup/InstallData.php.

<?php
namespace BSS\HelloWorld\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
       private $eavSetupFactory;
       public function __construct(EavSetupFactory $eavSetupFactory)
       {
              $this->eavSetupFactory = $eavSetupFactory;
       }
}

Step 2: Define the install() Method

After this step, we define the install() method and create eav setup model by using the code below:

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
       {
              $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
       }

And now, we use this eav setup model to create customer attribute in Magento 2:

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'sample_attribute',
[
'type' => 'varchar',
'label' => 'Sample Attribute',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'position' => 999,
'system' => 0,
]
);
}

Step 3: Create Custom Attribute

Finally, we set the forms for the attributes that will be used. For that, we need to define the eavConfig object that will allow us to call the attribute back and set the data.

<?php
namespace BSS\HelloWorld\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\Customer;
class InstallData implements InstallDataInterface
{
       private $eavSetupFactory;
       public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
       {
              $this->eavSetupFactory = $eavSetupFactory;
              $this->eavConfig       = $eavConfig;
       }
       public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
       {
              $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
              $eavSetup->addAttribute(
                     \Magento\Customer\Model\Customer::ENTITY,
                     'sample_attribute',
                     [
                            'type'         => 'varchar',
                            'label'        => 'Sample Attribute',
                            'input'        => 'text',
                            'required'     => false,
                            'visible'      => true,
                            'user_defined' => true,
                            'position'     => 999,
                            'system'       => 0,
                     ]
              );
              $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'sample_attribute');
              // more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
              $sampleAttribute->setData(
                     'used_in_forms',
                     ['adminhtml_customer']
              );
              $sampleAttribute->save();
       }
}

Now, let us run this command line to install the module:

php magento setup:upgrade and php bin/magento 
setup:static-content:deploy

>>> Dive into our comprehensive blog post and learn how to create, configure, and optimize your Magento 2 store for maximum performance and profitability: Magento 2 Step-by-Step Tutorial

Why Need to Create Customer Attribute in Magento 2?

Magento 2, with its default settings, offers a good foundation for understanding your customers. However, creating custom customer attributes unlocks a new level of personalization and insight, bringing several significant benefits, including:

Gather specific customer data: The default attributes might not capture everything you need to know about your customers. Custom attributes let you collect information tailored to your business, like loyalty program membership numbers, preferred communication methods (email/SMS), or even birthdays for targeted promotions.

Enhanced customer segmentation: With richer customer data, you can segment your audience more effectively. This allows for targeted marketing campaigns, personalized product recommendations, and loyalty programs that truly resonate with different customer groups.

Improved customer experience: By understanding your customers better, you can personalize their shopping journey. Imagine recommending relevant products based on past purchases or offering loyalty points for specific actions. This creates a more engaging and rewarding experience for your customers.

Deeper customer insights: Custom attributes provide valuable data for analyzing customer behavior and preferences. You can identify trends, understand purchase motivations, and optimize your store based on real customer data, leading to better decision-making.

Streamlined checkout process: While custom attributes are powerful, it’s important to use them strategically. Magento 2’s dependent attribute feature allows you to only display relevant fields based on customer selections, preventing lengthy forms that can lead to cart abandonment.

In the upcoming section, BSS Commerce will give the best solution to create customer attribute in Magento 2 and discuss specific features that help your Magento stores collect more valuable information.

Best Solution to Add Customer Attribute Magento 2

Understanding your customers is key to the success of online stores. Magento 2 offers built-in customer attributes, but what if you need to collect more specific information?

Don’t worry, this guide will explore the best solutions for adding custom customer attributes in Magento 2. We’ll delve into both user-friendly methods and the benefits of each approach, equipping you with the knowledge to gather the valuable customer insights you need to thrive.

Magento 2 Customer Attributes Extension BSS Commerce



A quick overview of the Magento 2 Customer Attributes Extension by BSS Commerce:

  • Compatible with Open Source (CE): 2.3.x – 2.4.x – Commerce On-Premise (EE): 2.3.x – 2.4.x
  • Compatible with Hyva theme & PHP 8.2
  • Cost: $79/one-time payment
  • Review: 91% positive
  • Update: Version 1.4.8 (May 10, 2024)

With a price of $79=per one-time payment, you’ll receive:

  • Free one-year support
  • Free lifetime update
  • Free Installation
  • 30 days money-back guarantee

Detailed features of the Magento 2 Customer Attributes extension:

1. Adding customer attributes with 9+ input types

9 input types. including:

  • Text Field
  • Dropdown
  • Text Area
  • Radio Button
  • Date & Time
  • Yes/No
  • Multiple Select
  • File (Attachment)
  • Checkbox

Magento 2 Customer Attributes Extension features 1

These 9 input types ensure that you can collect a wide range of information, including date of birth, images, and more!

2. Allow both administrators and customers to effortlessly handle attributes

Magento 2 includes custom attributes in the Account Information section, while address attributes are located in the Address Book. Customers can make changes to their information as needed. Any modifications made to customer attributes will be reflected in the relevant sections.

Magento 2 Customer Attributes Extension features 2

3. Easy to generate customer attributes for both the Magento 2 registration and checkout processes

Custom attributes enhance the checkout page by adding address attributes, thereby providing valuable information to buyers. This allows them to input additional details or notes for store owners, making the checkout process more informative and efficient.

Magento 2 Customer Attributes Extension features 3

4. Ensure that the added fields are prominently displayed in emails

Thanks to adding custom fields to customer address attributes on the account and order confirmation emails, you can easily notify customers about collected information and streamline the order implementation process.

Moreover, these customer address attributes are prominently displayed in various sales-related emails, such as order emails, invoice emails, shipment emails, and credit memo emails.

Magento 2 Customer Attributes Extension features 4

5. Add the attribute fields to the customer grid and order detail pages

This feature allows the administrator to efficiently handle all Magento customer attributes in the backend for maximum convenience.

Magento 2 Customer Attributes Extension features 5

6. Customize the order of attribute fields as desired

Through arranging the custom fields in Magento 2 in a logical sequence, customers can effortlessly complete the registration process and become proficient at it.

Furthermore, with the support of the Custom Attributes extension, you can:

  • Create or add customer attributes for Magento.
  • Specify whether the attribute is required or optional.
  • Customize the label for each store view.
  • Arrange the sort order of the attributes.
  • Select the location of the attributes in the form

Magento 2 Customer Attributes Extension features 6

7. Stay up-to-date with the latest features, including the ability to easily create and configure dependent attributes

Magento 2 introduces a new feature called “dependent customer attributes” to improve the customer registration and checkout experience. This allows you to show specific additional fields (child attributes) only when a customer selects a particular value in another field (parent attribute). This reduces form clutter and keeps the process smooth, preventing customer frustration and cart abandonment.

In addition, it provides valuable customer insights as those who complete all fields are likely more engaged, allowing you to better understand their behavior. This functionality extends to address attributes as well, and you can customize the display settings for both parent and child attributes independently.

>>> Full Guide on How to Install an Extension in Magento

The Bottom Line

To sum up, creating a customer attribute in Magento 2 is a great way to customize and enhance your understanding of your customers. It allows you to collect specific and relevant information that can be used to improve customer service, inform business strategies, and tailor marketing efforts. The process involves creating and installing a data patch and adding the attribute to the customer grid. While it requires some knowledge of Magento 2 and PHP, the benefits of having detailed customer insights make it a worthwhile endeavor.

For Magento stores, always remember to respect customer privacy and only collect the data that is necessary for your business needs. With the right approach, creating customer attributes in Magento 2 can significantly contribute to the success of your eCommerce business.

On the other hand, if you don’t have enough time and money to create customer attribute in Magento 2 store manually, consider the best solution provided above: “using the Magento 2 Customer Attributes extension.” Thanks to this extension, you can leverage maximum advanced features, save time and effort, and ensure the accuracy and safety of your online store.

Feel free to contact the BSS team with any inquiries regarding email sending or other facets of Magento’s online business, including Magento 2 development and Magento 2 extensions. BSS Commerce is here to assist you in achieving success in Magento.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.