0 Shares 7749 Views

How to add customer attribute in Magento 2.x

Moiz Khan Sep 19, 2016

Many of us are facing problems in adding custom attributes to customer profile in Magento 2. Here is how to add a custom field in Magento 2. Thanks to  sashas extension for providing easy solution on adding a custom field.

There are many ways to add custom field for customers in Magento 2. Today we will focus on extension for Magento 2 which adds attribute to customer edit page at admin.

To begin with you will need Magento 2 installed with demo data.  For more information you can see the Magento 2 installation guide.

Our step by step  instruction allow you to create a successful attribute of Customer in admin panel.

1) Creating pillar of Magento 2 Extension

You must have heard about the change in architecture of Magento with the release of Magento 2, but you don’t need to worry about it now. The extension files are placed exactly same way as it was in Magento 1.x. The extension files will be under app/code/(CompanyName)/(ExtensionName). For this tutorial the company name we will use is Sashas and extension name will be customerAttribute.

You can use you own company/extension name as per your need. We will create folders and path to the extension will be app/code/Sashas/CustomerAttribute/

The folder structure inside the extension folder in Magento 2 is quiet similar to Magento 1.x. We will need to create ‘etc’ and ‘setup’ folder inside the Magento extension folder.
The folder structure will look like this

                                                                    magento2_customer_attribute

In next step you will need to create module.xml file for extension to declare the version and visibility for Magento2. The module.xml file is replacement of for the previous module file under app/etc/modules folder. This way will lead all files of extension to be in one folder.

2) Creating Module file for Customer attribute in Magneto 2

For this tutorial, I assume you know how to create a file in Magento 2. Read here to know more about Magento file structure.
To begin with, we need to create the file app/code/Sashas/CustomerAttribute/etc/module.xml. This file will make the extension visible.

module.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * @author		Sashas
 * @category    Sashas
 * @package     Sashas_CustomerAttribute
 * @copyright   Copyright (c) 2015 Sashas IT Support Inc. (http://www.extensions.sashas.org) 
 */
-->
<config  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
   <module name="Sashas_CustomerAttribute"  setup_version="1.0.0">
        <sequence>           
            <module name="Magento_Customer"/>  
        </sequence>   
   </module>
</config> 

In the section we have defined the extension name and version. Here we used the name “Arpatech_CustomerAttr” and version = 1.0.0. You can use your own name of extension. Now we will add the list file. It will have the path app/code/Arpatech/customerAttr/Setup/InstallData.php. In next step we will create InstallData.php.

3) Creating CustomerInstallData file for Customer attribute in Magneto 2

The install function here is used to add attribute for entity “customer” and after it we set it to be used in form adminhtml_customer.
As per your requirement the customer attribute can be used in different forms. For this tutorial we will use this attribute in customer edit page in admin panel.

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

<?php
/**
 * @author		Sashas
 * @category    Sashas
 * @package     Sashas_CustomerAttribute
 * @copyright   Copyright (c) 2015 Sashas IT Support Inc. (http://www.extensions.sashas.org) 
 */

namespace Sashas\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;</pre>
<pre>
/**
 * @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' => 'Magento 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();
          
      
    }
}

As you can see we have used attribute code magento_name and we set the properties in similar way as Magento 1.x. After you get through with the code you need to launch Magento Upgrade and clean cache.

You can use shell command to launch Magento Upgrade:  php bin/magento setup:upgrade. This will perform all necessary upgrade for extension. After upgrading you will need to clear all the cache.

To clear the cache use the following shell command:  php bin/magento cache:flush-all

I hope now you will be able to create customized plugin in Magento 2.

Know how to save your store against brute force attack.

 

CMMI logo
Inxs anti vibration working gloves vibration and shock gloves anti impact mechanics breathable anti smashing safety gloves.