{{unknown}}

How to create custom customer attribute using Data patch in Magento 2

create custom customer attribute using Data patch magento 2

0 7

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 Data Patch which will be available in

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

Create the patch file in below path.

app\code\TechLeos\Datapatchs\Setup\Patch\Data\AddTelephoneAttribute.php

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

namespace TechLeos\Datapatchs\Setup\Patch\Data;

use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetup;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

/**
 * Patch is to recreate the telephone attribute
 */
class AddTelephoneAttribute implements DataPatchInterface
{
    /**
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;

    /**
     * @var ModuleDataSetupInterface
     */
    private $setup;

    /**
     * @var Config
     */
    private $eavConfig;

    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * AddCustomerAttributes constructor.
     *
     * @param ModuleDataSetupInterface $setup
     * @param Config $eavConfig
     * @param AttributeSetFactory $attributeSetFactory
     * @param CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $setup,
        Config $eavConfig,
        AttributeSetFactory $attributeSetFactory,
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->setup = $setup;
        $this->attributeSetFactory = $attributeSetFactory;
        $this->eavConfig = $eavConfig;
    }

    /**
     * Add our customer attribute here
     *
     * @return $this
     * @throws LocalizedException|\Zend_Validate_Exception
     * @throws \Exception
     */
    public function apply(): AddTelephoneAttribute
    {
        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory
            ->create(['setup' => $this->setup]);
        $customerEntity = $customerSetup->getEavConfig()
            ->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
        if (!$customerSetup->getAttributeId(Customer::ENTITY, 'telephone')) {
            $customerSetup->removeAttribute(Customer::ENTITY, 'telephone');
        }
        $customerSetup->addAttribute(
            Customer::ENTITY,
            'telephone',
            [
            'type' => 'varchar',
            'label' => 'Telephone',
            'input' => 'text',
            'sort_order' => 300,
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'system' => false,
            'is_visible_in_grid' => true,
            'is_used_in_grid' => true,
            'is_filterable_in_grid' => true,
            'is_searchable_in_grid' => true,
            'position' => 300
            ]
        );
        $telephoneAttribute = $this->eavConfig
            ->getAttribute(
                Customer::ENTITY,
                'telephone'
            );
        if ($telephoneAttribute !== null) {
            $telephoneAttribute->addData(
                [
                    'used_in_forms' => [
                        'adminhtml_customer',
                        'customer_account_edit',
                        'customer_account_create'
                    ],
                    'attribute_set_id' => $attributeSetId,
                    'attribute_group_id' => $attributeGroupId
                ]
            );
            $telephoneAttribute->save();
        }
        return $this;
    }

    /**
     * @inheritdoc
     * @return string[]
     */
    public static function getDependencies(): array
    {
        return [];
    }

    /**
     * @inheritdoc
     * @return string[]
     */
    public function getAliases(): array
    {
        return [];
    }
}

Please run below commands:

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.