Quickest Way to Add Customer Attributes in Magento 2 Registration Form

How to add custom field in Magento 2 registration form

by Stephanie Greene

Letting customers register to become members of your store is essential to retain visitors and turn them into loyal customers. Besides, a form with Magento’s default supported features cannot provide enough customization features for your store. So, this article will guide you on how to add custom field in Magento 2 registration form for your store with more advanced tools. 

How to add custom field in Magento 2 registration form

Step 1: Create a new customer attribute 

Firstly, we have to create a new attribute that stores the information that consumers enter while registering the form.

To build a new custom attribute, we will first create a new datapatch. After that, we will enter customer attributes into the database.

In Setup/Patch/Data/AddPhoneAttribute.php, use the following code:

 

<?php
namespace BSS\CustomerAttribute\Setup\Patch\Data;
use Magento\Catalog\Ui\DataProvider\Product\ProductCollectionFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Config;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;
use Psr\Log\LoggerInterface;
/**
* Class AddPhoneAttribute
* @package BSS\CustomerAttribute\Setup\Patch\Data
*/
class AddPhoneAttribute implements DataPatchInterface, PatchRevertableInterface
{
  /**
   * @var ModuleDataSetupInterface
   */
  private $moduleDataSetup;
  /**
   * @var EavSetupFactory
   */
  private $eavSetupFactory;
  /**
   * @var ProductCollectionFactory
   */
  private $productCollectionFactory;
  /**
   * @var LoggerInterface
   */
  private $logger;
  /**
   * @var Config
   */
  private $eavConfig;
  /**
   * @var \Magento\Customer\Model\ResourceModel\Attribute
   */
  private $attributeResource;
  /**
   * AddPhoneAttribute constructor.
   * @param EavSetupFactory $eavSetupFactory
   * @param Config $eavConfig
   * @param LoggerInterface $logger
   * @param \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
   */
  public function __construct(
      EavSetupFactory $eavSetupFactory,
      Config $eavConfig,
      LoggerInterface $logger,      \Magento\Customer\Model\ResourceModel\Attribute $attributeResource,      \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup
  ) {
      $this->eavSetupFactory = $eavSetupFactory;
      $this->eavConfig = $eavConfig;
      $this->logger = $logger;
      $this->attributeResource = $attributeResource;
      $this->moduleDataSetup = $moduleDataSetup;
  }
  /**
   * {@inheritdoc}
   */
  public function apply()
  {
      $this->moduleDataSetup->getConnection()->startSetup();
      $this->addPhoneAttribute();
      $this->moduleDataSetup->getConnection()->endSetup();
  }
  /**
   * @throws \Magento\Framework\Exception\AlreadyExistsException
   * @throws \Magento\Framework\Exception\LocalizedException
   * @throws \Zend_Validate_Exception
   */
  public function addPhoneAttribute()
  {
      $eavSetup = $this->eavSetupFactory->create();
      $eavSetup->addAttribute(
          \Magento\Customer\Model\Customer:: ENTITY,
          'phone_number',
          [
              'type' => 'varchar',
              'label' => 'Phone Number',
              'input' => 'text',
              'required' => 1,
              'visible' => 1,
              'user_defined' => 1,
              'sort_order' => 999,
              'position' => 999,
              'system' => 0
          ]
      );
      $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
      $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);
      $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'phone_number');
      $attribute->setData('attribute_set_id', $attributeSetId);
      $attribute->setData('attribute_group_id', $attributeGroupId);
      $attribute->setData('used_in_forms', [
          'adminhtml_customer',
      ]);
      $this->attributeResource->save($attribute);
  }
  /**
   * {@inheritdoc}
   */
  public static function getDependencies()
  {
      return [];
  }
  /**
   *
   */
  public function revert()
  {
  }
  /**
   * {@inheritdoc}
   */
  public function getAliases()
  {
      return [];
  }
}

Step 2: Show customer attribute in the customer registration form

In the next step, we need to display customers attribute in the registration form with 2 steps.

Firstly, in the BSS/CustomerAttribute/view/frontend/layout/customer_account_create.xml, add phtml files to “form.additional.info” reference name by the following code:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    layout="1column"    xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
      <referenceContainer name="form.additional.info">
          <block class="Magento\Framework\View\Element\Template"
                 name="phone_number"                 template="Magedelight_CustomerAttribute::extra_field.phtml"/>
      </referenceContainer>
  </body>
</page>

After that, use this command in /view/frontend/templates/extra_field.phtml to show an additional textbox. 

<div class="field phone_number required">
   <label class="label" for="phone_number">
       <span><?= $block->escapeHtml(__('Phone number')) ?></span>
   </label>
   <div class="control">
       <input type="text" name="phone_number" id="phone_number" value="" title="<?= $block->escapeHtmlAttr(__('Phone number')) ?>" class="input-text" data-validate="{required:true}">
   </div>
</div>

Now, the attribute will be shown on the customer registration page.

Step 3: Activate the customer attribute 

We almost complete to add new field in customer registration form Magento 2, the last step is only to activate it. Do it with the following command: 

php bin/magento setup:upgrade

Now, it’s done! Check the results. 

Wrap-up

Above is how to add custom field in Magento 2 registration form. Hopefully, with this guide, you can easily add new field in customer registration form Magento 2 with what you need. If you continue to receive the problem, thoroughly review the procedures outlined above to ensure that you followed them correctly. Don’t forget that we are always available here to help when you need anything further to improve your Magento store.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.