Magento – How to add custom field in registration form and add jquery validation in Magento2.2.5

custom-fieldjquerymagento2registrationvalidation

How to add custom field in registration form and save in database and add jquery validation in Magento2.2.5?

Any help would be appreciated

Best Answer

Adding a custom field in customer registration page

first if need then create a custom module follow this link

then need to create a file COMPANY\CUSTOMMODULE\Setup\InstallData.php to creating custom field

<?php

namespace COMPANY\CUSTOMMODULE\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
    private $eavSetupFactory;

    private $eavConfig;

    private $attributeResource;

    /**
     * InstallData constructor.
     * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
     * @param \Magento\Eav\Model\Config $eavConfig
     * @param \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
     */
    public function __construct(
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
    )
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeResource = $attributeResource;
    }

    /**
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @throws \Magento\Framework\Exception\AlreadyExistsException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $customField = "custom_field";
        $customFieldLabel = "Custom Field 1";
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $eavSetup->removeAttribute(Customer::ENTITY, $customField);

        $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
        $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);

        $eavSetup->addAttribute(Customer::ENTITY, $customField, [
            // Attribute parameters
            'type' => 'varchar',
            'label' => $customFieldLabel,
            'input' => 'text',
            'required' => true,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 990,
            'position' => 990,
            'system' => 0,
        ]);

        $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, $customField);
        $attribute->setData('attribute_set_id', $attributeSetId);
        $attribute->setData('attribute_group_id', $attributeGroupId);

        /*
        //You can use this attribute in the following forms
        adminhtml_checkout
        adminhtml_customer // for admin page under customer edit account info
        adminhtml_customer_address
        customer_account_create // for store-front registration page
        customer_account_edit // for store-front after logged-in account edit page
        customer_address_edit
        customer_register_address
        */

        $attribute->setData('used_in_forms', [
            'adminhtml_customer',
            'customer_account_create',
            'customer_account_edit'
        ]);

        $this->attributeResource->save($attribute);
    }
}

wait it will help to just create on DB level and visible in admin-level,

Need to access same custom field in store-front

so create a layout file COMPANY\CUSTOMMODULE\view\frontend\layout\customer_account_create.xml

<?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="Magento\Framework\View\Element\Template" name="form_additional_info_customer"
                   template="COMPANY_CUSTOMMODULE::additional.phtml"/>
        </referenceContainer>
    </body>
</page>

and to display field in store-front in registration page, create a phtml file COMPANY\CUSTOMMODULE\view\frontend\templates\additional.phtml

<?php
$customFieldLabel = __("Custom Field 1");
$customField = "custom_field";
?>
<div class="field <?= $customField ?> required">
    <label class="label" for="<?= $customField ?>">
        <span><?= $block->escapeHtml($customFieldLabel) ?></span>
    </label>
    <div class="control">
        <input type="text" name="<?= $customField ?>" id="<?= $customField ?>" value=""
               title="<?= $block->escapeHtmlAttr($customFieldLabel) ?>"
               class="input-text" data-validate="{required:true}">
    </div>
</div>

after added these files or code

run below commands :

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy (for developer mode add -f to command)

php bin/magento cache:clear

For JS validation : In above phtml file (COMPANY\CUSTOMMODULE\view\frontend\templates\additional.phtml), if you need to add custom validation then use Magento Validation classes to data-validate attribute.

More help for JS validation follow this link

Note : COMPANY\CUSTOMMODULE is the custom module, if you need you can change with your custom module.

Hope this will help you.