Magento 2: Add Customer Attribute Programmatically

Magento 2: Add Customer Attribute Programmatically

What’s the best way to improve customer loyalty and stay ahead of the competition? Based on our experience as a leading Magento extensions company, we believe that personalisation is the key to sustainable success. For personalisation, you need access to large amounts of customer data.

Undoubtedly, data is the new oil in today’s digital world. The more data you have, the more likely you are to succeed. Consider companies like Meta, Twitter, and others. While they claim to be social networking platforms, their success is tied with data. They offer unparalleled levels of insights into individual users to businesses.

This allows the businesses to serve these individuals with highly personalised ads. Magento 2, the platform allows merchants to add customer attributes. An attribute is simply an information that provides additional details on the customer or prospect. These attributes help store owners understand their audience better.

Although the default Magento 2 customer attributes are limited but Magento 2, being an open source and highly scalable platform allows to add custom attributes programmatically. Some examples of custom customer attributes are Date of Birth, Interests/Hobbies, Mobile number, ‘How did you find us?’, etc.

Ready Made Extension for Customer Attributes: Magento 2 Custom Registration Fields

About the Extension

If you don’t wish to create a customer attribute in Magento 2 programmatically, use our extension. Why? This extension is quite easy to set up and use. Apart from its user-friendliness, this extension offers a wide range of features that can transform your store. For example, you can add 13 different types of customer attributes as shown below through this extension.

attribute-properties

You can define any field as mandatory or optional. If you require a specific data type to enhance your pricing or marketing strategy, you can make the relevant fields as mandatory.

attribute-default-label

You can tailor each field to your liking. For instance, you can change their order, placement, and more. If you wish to know more about this extension, book a live demo.

3 Simple Steps to Add Customer Attribute Programmatically in Magento 2

Follow these steps to add the customer attribute programmatically:

Step 1: Create the Setup File InstallData.php

First of all, create the InstallData.php file: File Path: app/code/Company/Mymodule/Setup/InstallData.php
<?php
namespace Company\Mymodule\Setup;

use Magento\Eav\Model\Config;
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,
 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, 'custom_text_field', [
 'label' => 'Middle Name',
 'system' => 0,
 'position' => 700,
 'sort_order' => 700,
 'visible' => true,
 'note' => '',
 'type' => 'varchar',
 'input' => 'text',
 ]
 );

 $this->getEavConfig()->getAttribute('customer', 'custom_text_field')->setData('is_user_defined', 1)->setData('is_required', 0)->setData('default_value', '')->setData('used_in_forms', ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout'])->save();

 
 $eavSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_dropdown', [
 'label' => 'How did you hear about us?',
 'system' => 0,
 'position' => 700,
 'sort_order' => 700,
 'visible' => true,
 'note' => '',
 'type' => 'int',
 'input' => 'select',
 'source' => 'Company\Mymodule\Model\Source\Customdropdown',
 ]
 );

 $this->getEavConfig()->getAttribute('customer', 'custom_dropdown')->setData('is_user_defined', 1)->setData('is_required', 0)->setData('default_value', '')->setData('used_in_forms', ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout'])->save();

 
 $eavSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_yes_no', [
 'label' => 'Are you an existing customer?',
 'system' => 0,
 'position' => 700,
 'sort_order' => 700,
 'visible' => true,
 'note' => '',
 'type' => 'int',
 'input' => 'boolean',
 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
 ]
 );

 $this->getEavConfig()->getAttribute('customer', 'custom_yes_no')->setData('is_user_defined', 1)->setData('is_required', 0)->setData('default_value', '')->setData('used_in_forms', ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout'])->save();
 }
 
 public function getEavConfig() {
 return $this->eavConfig;
 }
}

The above code will create the following three custom attributes.

Middle Name → Text Field

How did you hear about us? → Dropdown

Are you an existing customer? → Yes/No

“How did you hear about us?” is a select box and we have defined a custom source: Company\Mymodule\Model\Source\Customdropdown So, we need to create the source file as well.

Similarly, if you are looking for Magento 2 add customer address attribute programmatically, just follow the same instructions.

Step 2: Create the Source File

Now, create the Source File File Path: app/code/Company/Mymodule/Model/Source/Customdropdown.php
<?php

namespace Company\Mymodule\Model\Source;

class Customdropdown extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource 
{
 public function getAllOptions() 
 {
 if ($this->_options === null) {

 $this->_options = [

 ['value' => '', 'label' => __('Please Select')],

 ['value' => '1', 'label' => __('Google')],

 ['value' => '2', 'label' => __('Friend')],

 ['value' => '3', 'label' => __('Email')],

 ['value' => '4', 'label' => __('Other')]

 ];

 }

 return $this->_options;

 }

 public function getOptionText($value) 
 {
 foreach ($this->getAllOptions() as $option)
 {
 if ($option['value'] == $value)
 {
 return $option['label'];
 }
 }
 return false;
 }
}

Step 3: Upgrade

Open terminal/SSH and navigate to Magento 2 setup root directory and run the commands below.
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f

Moreover, you can add other types of fields like customer address attribute, radio buttons, contact number field, etc. using above script.

You can also check more details regarding customer attributes in this magento user guide.

Final Thoughts on Magento 2 Add Customer Attribute Programmatically

If you have any issue in adding custom customer attribute programmatically in Magento 2, then feel free to contact our support team for a quick fix.