{{unknown}}

How To Create Custom Customer Attribute Using Install Data in Magento 2

Create Custom Customer Attribute Using Install Data In Magento 2

0 15

An attribute is a property of an entity that can be used in various Magento 2 store’s function.

Here we’ll talk about how to create custom customer telephone attribute field in Magento 2 using Install Data which will be available in

  • Customer account registration form,
  • Customer account section
  • In Admin, customer information tab

InstallData will work at the time of module installation.

app\code\TechLeos\Datapatchs\Setup\InstallData.php

<?php
/**
 * @package     TechLeos/Datapatchs
 * @author      TechLeos<code@techleos .com>
 * @copyright   Copyright © TechLeos. All rights reserved.
 */
declare(strict_types=1);

namespace TechLeos\Datapatchs\Setup;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\Customer;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;


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(
            Customer::ENTITY,
            'telephone',
            [
                'type'         => 'varchar',
                'label'        => 'Telephone',
                'input'        => 'text',
                'required'     => false,
                'user_defined' => true,
                'position'     => 999,
                'visible'      => true,                
                'system'       => 0,
            ]
        );
        $telephoneAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'telephone');
        $telephoneAttribute->setData(
            'used_in_forms',
            [
                'adminhtml_customer',
                'customer_account_edit',
                'customer_account_create'
            ]

        );
        $telephoneAttribute->save();
    }
}

Please run below commands

php bin/magento module:enable TechLeos_Datapatchs
php bin/magento setup:upgrade
php bin/magento cache:clean

Any doubts or clarification about the solution can be mentioned in the Comments section below.

Thank you!

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.