Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Add Customer Attribute Programmatically in Magento 2?

Vinh Jacker | 12-18-2024

How to Add Customer Attribute Programmatically in Magento 2?

This article will guide you on how to add customer attributes in Magento 2 programmatically. Please follow our previous article to create a simple module that we will use to demo coding for this lesson and how to create the setup script classes. In this article, we will use the sample module Mageplaza_HelloWorld and the InstallDataclass.

Recommend:

Use Magento 2 Customer Attributes to add extra attribute fields to collect valuable customer information on the registration or account page.

Overview of Adding Customer Attribute Programmatically

Step 1: Create setup file InstallData.php

Firstly, we will create the InstallData.php file:

File: app/code/Mageplaza/HelloWorld/Setup/InstallData.php

<?php
namespace Mageplaza\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;
	}

}

In this class, we define the EAV setup model which will be used to interact with the Magento 2 attribute.

Step 2: Define the install() method

After that, we have to define the install() method and create eav setup model:

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
	{
		$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
	}
	Next, we will use eavSetup object to add attribute:
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 need to set the forms in which the attributes will be used. In this step, we need to define the eavConfig object which allows us to call the attribute back and set the data for it. And the full code to create customer attributes is:

File: app/code/Mageplaza/HelloWorld/Setup/InstallData.php

<?php

namespace Mageplaza\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’s run a command line to install the module: php magento setup:upgrade and php bin/magento setup:static-content:deploy Then check the result. It will show like this:

customer attribute

Related Topics

x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services