Magento2 | PWA | GraphQL

How To Add Custom/New Field In Magento 2 Customer Registration Form


In this post we wiil check how to add new/custom field in Magento2 Customer registration form.

This custom attribute (customer mobile) will appear on Customer admin grid, Customer dashboard, Customer edit account, and customer registration form.

Let's start by creating custom module.

You can find complete module on Github at Magelearn_CustomerMobile








 Add registration.php file in it:

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Magelearn_CustomerMobile',
    __DIR__
);

Add composer.json file in it:

{
    "name": "magelearn/module-customermobile",
    "description": "Add custom attribute (Customer Mobile) to customer entity. This custom attribute will appear on Customer admin grid, Customer dashboard, Customer edit account, and customer registration form.",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@mage2gen.com",
            "name": "Mage2Gen"
        },
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\CustomerMobile\\": ""
        }
    }
}

Add etc/module.xml file in it:

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_CustomerMobile" setup_version="0.0.1" >
    </module>
</config>

Now we will add database installation script to add this customer attribute (customer mobile) properly.

Create app/code/Magelearn/CustomerMobile/Setup/InstallData.php file.

<?php

namespace Magelearn\CustomerMobile\Setup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

class InstallData implements InstallDataInterface{

    private $_eavSetupFactory;
    private $_eavConfig;
    private $_customerSetupFactory;
    private $_attributeSetFactory;

    public function __construct(
        EavSetupFactory $eavSetupFactory,
        Config $eavConfig,
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ){
        $this->_eavSetupFactory = $eavSetupFactory;
        $this->_eavConfig       = $eavConfig;
        $this->_customerSetupFactory = $customerSetupFactory;
        $this->_attributeSetFactory = $attributeSetFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){

        /*Customer Module Setup*/
        $customerSetup = $this->_customerSetupFactory->create(['setup' => $setup]);
        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        /*Get Default Attribute Set*/
        $attributeSet = $this->_attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);


        /*$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);*/

        $setup->startSetup();

        /*Attribute Params*/
        $attributeParams=[
            'type'                  => 'varchar',
            'label'                 => 'Customer Mobile',
            'input'                 => 'text',
            'required'              => false,
            'unique'                => false,
            'visible'               => true,
            'user_defined'          => true,
            'position'              => 100,
            'system'                => false,
            'is_used_in_grid'       => true,
            'is_visible_in_grid'    => true,
            'is_filterable_in_grid' => true,
            'is_searchable_in_grid' => true,
            'validate_rules' => '{"max_text_length":14,"input_validation":"number"}'];

        $customerSetup->addAttribute(Customer::ENTITY, 'customer_mobile', $attributeParams);
        $attribute = $customerSetup->getEavConfig()
            ->getAttribute(Customer::ENTITY, 'customer_mobile')
            ->addData(
                [
                    'attribute_set_id' => $attributeSetId,
                    'attribute_group_id' => $attributeGroupId,
                    'used_in_forms'=> [
                        'adminhtml_customer',
                        'customer_account_create',
                        'customer_account_edit'
                    ]
                ]
            );
        $attribute->save();
        $setup->endSetup();
    }
}

Now to display this custom customer attribute properly on front end we will add our layout and template files.
Add app/code/Magelearn/CustomerMobile/view/frontend/layout/customer_account_create.xml file.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <!-- add mobile to registration-->
        <referenceContainer name="form.additional.info">
            <block class="Magelearn\CustomerMobile\Block\Widget\CustomerMobile" name="customer_mobile" template="Magelearn_CustomerMobile::register/customer_mobile.phtml"  />
        </referenceContainer>
    </body>
</page>

Add app/code/Magelearn/CustomerMobile/view/frontend/layout/customer_account_edit.xml file.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="form.additional.info">
            <block class="Magelearn\CustomerMobile\Block\Widget\CustomerMobile" name="customer_mobile" template="Magelearn_CustomerMobile::widget/customer_mobile.phtml" cacheable="false" />
        </referenceContainer>
    </body>
</page>

Add app/code/Magelearn/CustomerMobile/view/frontend/layout/customer_account_index.xml file

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_account_dashboard_info">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Magelearn_CustomerMobile::customer/account/dashboard/info.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Now we will add our block file at app/code/Magelearn/CustomerMobile/Block/Widget/CustomerMobile.php file.

<?php

namespace Magelearn\CustomerMobile\Block\Widget;


class CustomerMobile extends \Magento\Customer\Block\Widget\AbstractWidget {

    /*Attribute Code is customer_mobile*/
    const ATTRIBUTE_CODE = 'customer_mobile';

    protected $_customerMetadata;
    protected $_addressHelper;
    protected $_customerSession;
    protected $_customerRepository;
    protected $options;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context         $context,
        \Magento\Customer\Model\Options                          $options,
        \Magento\Customer\Helper\Address                         $addressHelper,
        \Magento\Customer\Api\CustomerMetadataInterface          $customerMetadata,
        \Magento\Customer\Model\SessionFactory                   $customerSession,
        \Magento\Customer\Model\Customer                         $customerModel,

        array $data = []
    ) {
        $this->options = $options;
        parent::__construct($context, $addressHelper, $customerMetadata, $data);
        $this->_customerMetadata=$customerMetadata;
        $this->_addressHelper=$addressHelper;
        $this->_customerSession = $customerSession;
        $this->_customerRepository = $customerModel;
        $this->_isScopePrivate = true;
    }

    public function _construct()
    {
        parent::_construct();

        // default template location
        $this->setTemplate('widget/customer_mobile.phtml');
    }

    /* Check attribute property 'visible' */
    public function isEnabled(){

        return $this->_getAttribute(self::ATTRIBUTE_CODE) ? (bool)$this->_getAttribute(self::ATTRIBUTE_CODE)->isVisible() : false;
    }

    /* Check for required property*/
    public function isRequired(){
        return $this->_getAttribute(self::ATTRIBUTE_CODE) ? (bool)$this->_getAttribute(self::ATTRIBUTE_CODE)
            ->isRequired() : false;
    }

    /* Get validation rules 'url validate','max length'*/
    public function getAttributeValidationClass(){
        return $this->_getAttribute(self::ATTRIBUTE_CODE)->getFrontendClass();
    }

    protected function _getAttribute($attributeCode){
        try {
            return $this->_customerMetadata->getAttributeMetadata($attributeCode);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return null;
        }
    }

    /* Get Customer to get attribute value*/
    public function getCustomer(){
        $sessionModel = $this->_customerSession->create();
        return $this->_customerRepository->load($sessionModel->getCustomer()->getId());
    }

    /* Return attribute value*/
    public function getCustomerMobile(){
        return $this->getCustomer()->getCustomerMobile();
    }

}

Now add template file at app/code/Magelearn/CustomerMobile/view/frontend/templates/register/customer_mobile.phtml file.

<?php

/** @var \Magelearn\CustomerMobile\Block\Widget\CustomerMobile $block */
?>
<?php if ($block->isEnabled()): ?>
    <div class="fieldset info">
        <div class="field field-mobile-number <?= $block->isRequired() ? 'required' : '' ?>">
            <label for="mobile-number" class="label">
        <span>
            <?= $block->escapeHtml(__('Mobile Number')) ?>
        </span>
            </label>
            <div class="control">
                <?php
                $_validationClass = $block->getAttributeValidationClass();
                ?>
                <input type="text"
                       name="customer_mobile"
                       id="customer_mobile"
                       title="<?= $block->escapeHtmlAttr(__('Mobile Number')) ?>"
                       class="input-text <?= $_validationClass ?: '' ?>"

                >
            </div>
        </div>
    </div>
<?php endif; ?>

Another template file at app/code/Magelearn/CustomerMobile/view/frontend/templates/widget/customer_mobile.phtml file.

<?php

/** @var \Magelearn\CustomerMobile\Block\Widget\CustomerMobile $block */
?>
<?php if ($block->isEnabled()): ?>
    <div class="fieldset info">
        <div class="field field-github-url <?= $block->isRequired() ? 'required' : '' ?>">
            <label for="fax" class="label">
        <span>
            <?= $block->escapeHtml(__('Mobile Number')) ?>
        </span>
            </label>
            <div class="control">
                <?php
                $_validationClass = $block->getAttributeValidationClass();
                ?>
                <input type="text"
                       name="customer_mobile"
                       value="<?= $block->escapeHtmlAttr($block->getCustomerMobile()) ?>"
                       id="customer_mobile"
                       title="<?= $block->escapeHtmlAttr(__('Mobile Number')) ?>"
                       class="input-text <?= $_validationClass ?: '' ?>"

                >
            </div>
        </div>
    </div>
<?php endif; ?>

Another template file at app/code/Magelearn/CustomerMobile/view/frontend/templates/customer/account/dashboard/info.phtml file.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var \Magento\Customer\Block\Account\Dashboard\Info $block */
?>
<div class="block block-dashboard-info">
    <div class="block-title"><strong><?= $block->escapeHtml(__('Account Information')) ?></strong></div>
    <div class="block-content">
        <div class="box box-information">
            <strong class="box-title">
                <span><?= $block->escapeHtml(__('Contact Information')) ?></span>
            </strong>
            <div class="box-content">
                <p>
                    <?= $block->escapeHtml($block->getName()) ?><br>
                    <?= $block->escapeHtml($block->getCustomer()->getEmail()) ?><br>
                    <?php $mobileAttribute = $block->getCustomer()->getCustomAttribute('customer_mobile'); ?>
                    <?php if ($mobileAttribute): ?>
                        <?php echo $mobileAttribute->getValue(); ?>
                    <?php endif; ?>
                </p>
                <?= $block->getChildHtml('customer.account.dashboard.info.extra'); ?>
            </div>
            <div class="box-actions">
                <a class="action edit" href="<?= $block->escapeUrl($block->getUrl('customer/account/edit')) ?>">
                    <span><?= $block->escapeHtml(__('Edit')) ?></span>
                </a>
                <a href="<?= $block->escapeUrl($block->getChangePasswordUrl()) ?>" class="action change-password">
                    <?= $block->escapeHtml(__('Change Password')) ?>
                </a>
            </div>
        </div>
        <?php if ($block->isNewsletterEnabled()): ?>
            <div class="box box-newsletter">
                <strong class="box-title">
                    <span><?= $block->escapeHtml(__('Newsletters')) ?></span>
                </strong>
                <div class="box-content">
                    <p>
                        <?php if ($block->getIsSubscribed()): ?>
                            <?= $block->escapeHtml(__('You are subscribed to "General Subscription".')) ?>
                        <?php else: ?>
                            <?= $block->escapeHtml(__('You aren\'t subscribed to our newsletter.')) ?>
                        <?php endif; ?>
                    </p>
                </div>
                <div class="box-actions">
                    <a class="action edit" href="<?= $block->escapeUrl($block->getUrl('newsletter/manage')) ?>">
                        <span><?= $block->escapeHtml(__('Edit')) ?></span></a>
                </div>
            </div>
        <?php endif; ?>
        <?= $block->getChildHtml('additional_blocks'); ?>
    </div>
</div>
Now we will also display customer's mobile number in admin dashboard at Customer Information >> Customer View >> Personal information section.

For that add view/adminhtml/layout/customer_index_edit.xml file.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="personal_info">
            <block class="Magelearn\CustomerMobile\Block\Adminhtml\Customer\Edit\Tab\View\PersonalInfo" name="magelearn_customermobile_personalinfo" template="Magelearn_CustomerMobile::customer/tab/view/personal_info.phtml" after="-">
            </block>
        </referenceBlock>
    </body>
</page>

Now as per highlighted code above add a block file and template file.

Add block file at Block/Adminhtml/Customer/Edit/Tab/View/PersonalInfo.php

<?php

namespace Magelearn\CustomerMobile\Block\Adminhtml\Customer\Edit\Tab\View;

use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Address\Mapper;
use Magento\Backend\Block\Template\Context;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Helper\Address;
use Magento\Framework\Stdlib\DateTime;
use Magento\Framework\Registry;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Customer\Model\Logger;

class PersonalInfo extends \Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo
{
    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param AccountManagementInterface $accountManagement
     * @param \Magento\Customer\Api\GroupRepositoryInterface $groupRepository
     * @param \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerDataFactory
     * @param \Magento\Customer\Helper\Address $addressHelper
     * @param \Magento\Framework\Stdlib\DateTime $dateTime
     * @param \Magento\Framework\Registry $registry
     * @param Mapper $addressMapper
     * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
     * @param \Magento\Customer\Model\Logger $customerLogger
     * @param array $data
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        Context $context,
        AccountManagementInterface $accountManagement,
        GroupRepositoryInterface $groupRepository,
        CustomerInterfaceFactory $customerDataFactory,
        Address $addressHelper,
        DateTime $dateTime,
        Registry $registry,
        Mapper $addressMapper,
        DataObjectHelper $dataObjectHelper,
        Logger $customerLogger,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $accountManagement,
            $groupRepository,
            $customerDataFactory,
            $addressHelper,
            $dateTime,
            $registry,
            $addressMapper,
            $dataObjectHelper,
            $customerLogger,
            $data
        );
    }

    public function getCustomerObject()
    {
        return $this->getCustomer();
    }
}

Add template file at view/adminhtml/templates/customer/tab/view/personal_info.phtml

<?php
    /** @var \Magelearn\CustomerMobile\Block\Adminhtml\Customer\Edit\Tab\View\PersonalInfo $block */
    $customer = $block->getCustomerObject();
    $mobileAttribute = $customer->getCustomAttribute('customer_mobile');
?>
<tr>
    <th><?= $block->escapeHtml(__('Customer Mobile')) ?></th>
    <td><?= $block->escapeHtml($mobileAttribute ? $mobileAttribute->getValue() : '') ?></td>
</tr>
0 Comments On "How To Add Custom/New Field In Magento 2 Customer Registration Form"

Back To Top