How to Add Custom Customer Attribute in Magento 2?

  • Posted by Envision Ecommerce
  • /
  • May 11, 2016
How-To-Add-Custom-Customer-Attribute-in-Magento-2

When Magento 2 was about to release, we realized that how the custom attribute adding process would have been revamped. With such a particular thing in the mind, we have taken some initiate actions, and now guiding you by creating a Magento 2 extension that will positively add custom customer attribute into customer edit page at admin.

First of all, make sure that you have installed Magento 2 with Demo data. You can take installation guidance from Magento 2 Developer Documentation (http://devdocs.magento.com/guides/v2.0/install-gde/continue.html).

  1. Start to Create Magento 2 Extension Framework

At the very first moment, the extension files will be accessible at the app/code/ {Company_Name}/{Extension_Name} site. Where {Company_Name} and {Extension_Name} our values. Similarly, the way it was in Magento 1.x.p>

In our extension, we are using company name Eecom and Extension name CustomAttribute. Once, after creating the folders, our extension can be accessed through this path,  app/code/Eecom/CustomAttribute/

The structure of the folder contained by extension folder is extremely similar to Magento 1.x. Folders like Controller, Helper, etc, Block and Model all are quite the same. However, in our case, the final look of our folder for our Magento 2 extension will seem like below:

As we move on to the next, we need to make module.xml file for our extension in order to declare version as well as to make it observable for Magento 2.

In Magento 1.x., the module file at app/etc/modules folder and now in new version, it has been replaced with the module.xml file. Now, all files associated with our extension, have been displayed in a single folder.

  1. Magento 2 Custom Customer Attribute Module Files

The very first file, we require to create is – app/code/Eecom/CustomAttribute/etc/module.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--

/**

* @author              Eecom

* @category    Eecom

* @package     Eecom_CustomAttribute

* @copyright   Copyright (c) 2016 Eecom IT Support Inc. (http://demo.envisionecommerce.com/store/)

*/

-->

<config  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

<module name="Eecom_CustomAttribute"  setup_version="1.0.0">

<sequence>

<module name="Magento_Customer"/>

</sequence>

</module>

</config>

This file allows our extension to get discernible for Magento and we can easily state dependency our customer attribute extension from the Magento_Customer module.

For the definition of extension name and version, you can check that at <module/> section.

The second and the list file we have added it in Installation script.

The path of this can be easily accessible on- app/code/Eecom/CustomAttribute/Setup/InstallData.php

The entire action happens during install function, where we include a custom attribute for entity type “customer” and later on, we can use this attribute in form “adminhtml_customer”.

We can make use of custom Customer attributes in various forms. The following is a mentioned example that will exhibit custom customer attribute at the admin customer edit page. You also have a facility to use it in other forms like:

“used_in_forms” =>  [‘adminhtml_customer_address’, ‘customer_address_edit’, ‘customer_register_address’]

The last and final code of the InstallData.php file will display like the following:

<?php

/**

* @author              Eecom

* @category    Eecom

* @package     Eecom_CustomAttribute

* @copyright   Copyright (c) 2016 Envision Ecommerce. (http://demo.envisionecommerce.com/store/)

*/

namespace Eecom\CustomerAttribute\Setup;

use Magento\Customer\Setup\CustomerSetupFactory;

use Magento\Customer\Model\Customer;

use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;

use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

use Magento\Framework\Setup\InstallDataInterface;

use Magento\Framework\Setup\ModuleContextInterface;

use Magento\Framework\Setup\ModuleDataSetupInterface;

/**

* @codeCoverageIgnore

*/

class InstallData implements InstallDataInterface

{

/**

* @var CustomerSetupFactory

*/

protected $customerSetupFactory;

/**

* @var AttributeSetFactory

*/

private $attributeSetFactory;

/**

* @param CustomerSetupFactory $customerSetupFactory

* @param AttributeSetFactory $attributeSetFactory

*/

public function __construct(

CustomerSetupFactory $customerSetupFactory,

AttributeSetFactory $attributeSetFactory

) {

$this->customerSetupFactory = $customerSetupFactory;

$this->attributeSetFactory = $attributeSetFactory;

}

/**

* {@inheritdoc}

*/

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)

{

/** @var CustomerSetup $customerSetup */

$customerSetup = $this->customerSetupFactory->create([‘setup’ => $setup]);

$customerEntity = $customerSetup->getEavConfig()->getEntityType(‘customer’);

$attributeSetId = $customerEntity->getDefaultAttributeSetId();

/** @var $attributeSet AttributeSet */

$attributeSet = $this->attributeSetFactory->create();

$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(Customer::ENTITY, ‘magento_username’, [

‘type’ => ‘varchar’,

‘label’ => ‘Custom Username’,

‘input’ => ‘text’,

‘required’ => false,

‘visible’ => true,

‘user_defined’ => true,

‘sort_order’ => 1000,

‘position’ => 1000,

‘system’ => 0,

]);

$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, ‘magento_username’)

->addData([

‘attribute_set_id’ => $attributeSetId,

‘attribute_group_id’ => $attributeGroupId,

‘used_in_forms’ => [‘adminhtml_customer’],

]);

$attribute->save();

}

}

In this example, you can check that we have used attribute code “magento_username” in 68-76 lines, where we put the properties of the attribute. And, these properties look alike to the Magento 1.x values.

Once we are done with the code, we have to start launching Magento upgrade and clear cache. Launch Magento 2 upgrade, we can from the shell by using command:

php bin/magento  setup:upgrade

This will undergo installed extension and execute upgrade or extension installation by means of data and database tables.

We can also make cache clear with the help of shell command:

 php bin/magento  cache:flush –all

  1. The Consequence

In the consequence, we can notice that our field comes in General Tab at the admin of Magento 2 customer edit page:

magento2_customer_attribute_admin

We hope aforementioned guidelines would help you with discovering new Magento 2 platform. If still you are facing any difficulties, then contact us, our certified Magento developers will serve you with best possible Magento 2 custom customer attribute solution.