Reading list Switch to dark mode

    How to Create Customer Custom Attribute in Magento 2

    Updated 20 November 2023

    Here we will learn, How to create Customer Custom attribute in Magento 2. Also, know how you can create custom Magento 2 attribute for your multi vendor marketplace.

    Image


    We can achieve this by using the following methods:

    1st Method: Using InstallData file
    Create the file Webkul\CustomAttribute\Setup\InstallData.php

    <?php
    namespace Webkul\CustomAttribute\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;
    
    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;
        }
     
        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, 'custom_cust_attribute', [
                'type' => 'varchar',
                'label' => 'Custom Attribute',
                'input' => 'text',
                'required' => false,
                'visible' => true,
                'user_defined' => true,
                'position' => 999,
                'system' => 0,
            ]);
    
            $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_cust_attribute')
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer'],//you can use other forms also ['adminhtml_customer_address', 'customer_account_edit', 'customer_address_edit', 'customer_register_address', 'customer_account_create']
            ]);
    
            $attribute->save();
        }
    }

    InstallData conforms to InstallDataInterface , which requires the implementation of the install method that accepts two parameters of type ModuleDataSetupInterface and ModuleContextInterface .
    Using the addAttribute method on the instance of Magento\Customer\Setup\CustomerSetupFactory, we are instructing Magento to add a number of attributes.
    Note: The module’s module.xml file must have setup_version to create customer custom attribute using InstallData. To know steps to create module in Magento2,  you can check our another blog here.


    2nd Method: Using Data Patch
    In this method, we need to create a data patch file as CreateAttributes.php in our custom module Setup folder. Note: You can also use the different file name and class name.
    complete path: app/code/Webkul/CustomAttribute/Setup/Patch/Data/CreateAttributes.php

    To know more about data and schema patches, click here.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    <?php
    namespace Webkul\CustomAttribute\Setup\Patch\Data;
    
    use Magento\Framework\Setup\Patch\DataPatchInterface;
    use Magento\Customer\Setup\CustomerSetupFactory;
    use Magento\Customer\Model\Customer;
    use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    
    class CreateAttributes implements DataPatchInterface
    {
        /**
         * @var ModuleDataSetupInterface
         */
        private $moduleDataSetup;
    
        /**
         * @var CustomerSetupFactory
         */
        protected $customerSetupFactory;
    
        /**
         * @var AttributeSetFactory
         */
        private $attributeSetFactory;
    
        /**
         * @param ModuleDataSetupInterface $moduleDataSetup
         * @param CustomerSetupFactory $customerSetupFactory
         * @param AttributeSetFactory $attributeSetFactory
         */
        public function __construct(
            ModuleDataSetupInterface $moduleDataSetup,
            CustomerSetupFactory $customerSetupFactory,
            AttributeSetFactory $attributeSetFactory
        ) {
            $this->moduleDataSetup = $moduleDataSetup;
            $this->customerSetupFactory = $customerSetupFactory;
            $this->attributeSetFactory = $attributeSetFactory;
        }
    
        /**
         * Add eav attributes
         */
        public function apply()
        {
            /** @var CustomerSetup $customerSetup */
            $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
    
            $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
            $attributeSetId = $customerEntity->getDefaultAttributeSetId();
    
            /** @var $attributeSet AttributeSet */
            $attributeSet = $this->attributeSetFactory->create();
            $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
    
            $customerSetup->addAttribute(Customer::ENTITY, 'custom_customer_attribute', [
                'type' => 'varchar',
                'label' => 'Custom Attribute',
                'input' => 'text',
                'required' => false,
                'visible' => true,
                'user_defined' => true,
                'position' => 999,
                'system' => 0,
            ]);
    
            $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_customer_attribute')
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer'],//you can use other forms also ['adminhtml_customer_address', 'customer_account_edit', 'customer_address_edit', 'customer_register_address', 'customer_account_create']
            ]);
    
            $attribute->save();
        }
    
        /**
         * Get dependencies
         */
        public static function getDependencies()
        {
            return [];
        }
    
        /**
         * Get Aliases
         */
        public function getAliases()
        {
            return [];
        }
    }


    After adding these files, run the following command in your magento2 root directory through terminal.

    php bin/magento setup:upgrade

    That is all for the How to Create Customer Custom Attribute in Magento 2. Hope it will help you. Thank you.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    4 comments

  • Mohit Arora
    Thanks.. I was getting error in the constructor. Thanks for such simple and easy to understand post.
    • Webkul Support
      Hi Mohit,
      I hope you are facing this error:
      [MagentoFrameworkExceptionLocalizedException] The attribute code ‘custom_attribute’ is reserved by system. Please try another attribute code

      This is because the attribute code with this name is already taken by the system. try with other attribute code.
      Replace “custom_attribute” with “my_custom_attribute” in your code.

      Mahesh SinghSr. Software Engineer (Magento)

      Webkul Software Pvt. Ltd. Contact : India (+91)-9650486699 USA (+1)-9143531684

      A 67 Sector 63 ,
      Noida-201301 (U.P.)
      India

      http://webkul.com

      This email and any files transmitted with it are confidential and contain privileged or copyright information. If you are not the intended recipient you must not disseminate, copy, distribute, or use this email or the information contained in it for any purpose other than to notify us. If you have received this message in error, please notify the sender immediately, and delete this email from your system.

  • Kirti Nariya
    How to show customer created attributes in front Billing and customer registration form magento 2
  • Jarnail
    How to add more than one attributes?
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home