0

I need to add an affiliate email field for customer registration form .

Here are the files I used

app/design/frontend/vendor/theme/Magento_Customer/templates/form/register.phtml

      <div class="field ">
        <label for="custom_field" class="label"><span><?= __('affiliateEmail') ?></span></label>
        <div class="control">
            <input type="text" name="affiliate_email" id="affiliate_email" value="<?= $block->escapeHtml($block->getFormData()->getCustomField()) ?>" title="<?= __('affiliateEmail') ?>" class="input-text" data-validate="{required:false,'validate-email':true}">
        </div>
    </div>

app/code/vendor/module/setup/InstallData.php

namespace Vendor\module\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;

/**
 * Install data
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{

    /**
     * CustomerSetupFactory
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;

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

    /**
     * initiate object
     * @param CustomerSetupFactory $customerSetupFactory
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    )
    {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    /**
     * install data method
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    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);
        /**
         * customer registration form  affiliate email address
         */
        $customerSetup->addAttribute(Customer::ENTITY, 'affiliate_email', [
            'type' => 'varchar',
            'label' => 'Affiliate Email',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 1000,
            'position' => 1000,
            'system' => 0,
        ]);
        //add attribute to attribute set
        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'affiliate_email')
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer', 'customer_account_create'],
            ]);

        $attribute->save();


    }
}

}

0

Create extension

step1: /app/code/Customer/Attribute/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Customer_Attribute',
    __DIR__
);

step2: /app/code/Customer/Attribute/Setup/CustomerSetup.php

<?php

namespace Customer\Attribute\Setup;

use Magento\Eav\Model\Config;
use Magento\Eav\Model\Entity\Setup\Context;
use Magento\Eav\Setup\EavSetup;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory;

class CustomerSetup extends EavSetup {

    protected $eavConfig;

    public function __construct(
        ModuleDataSetupInterface $setup,
        Context $context,
        CacheInterface $cache,
        CollectionFactory $attrGroupCollectionFactory,
        Config $eavConfig
        ) {
        $this -> eavConfig = $eavConfig;
        parent :: __construct($setup, $context, $cache, $attrGroupCollectionFactory);
    } 

    public function installAttributes($customerSetup) {
        $this -> installCustomerAttributes($customerSetup);
        $this -> installCustomerAddressAttributes($customerSetup);
    } 

    public function installCustomerAttributes($customerSetup) {


        $customerSetup -> addAttribute(\Magento\Customer\Model\Customer::ENTITY,
            'affiliate_email',
            [
            'label' => 'Affiliate Email',
            'system' => 0,
            'position' => 100,
            'sort_order' =>100,
            'visible' =>  true,
            'note' => '',


                        'type' => 'varchar',
                        'input' => 'text',

            ]
            );

        $customerSetup -> getEavConfig() -> getAttribute('customer', 'affiliate_email')->setData('is_user_defined',1)->setData('is_required',0)->setData('default_value','')->setData('used_in_forms', ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout']) -> save();


    } 

    public function installCustomerAddressAttributes($customerSetup) {

    } 

    public function getEavConfig() {
        return $this -> eavConfig;
    } 
} 

step 3: /app/code/Customer/Attribute/Setup/InstallData.php

<?php

namespace Customer\Attribute\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        if (version_compare($context->getVersion(), '1.0.0') < 0){

                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $customerSetup = $objectManager->create('Customer\Attribute\Setup\CustomerSetup');
                $customerSetup->installAttributes($customerSetup);



        }

    }
}

step4: /app/code/Customer/Attribute/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Customer_Attribute" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Backend"/>
             <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Checkout"/>
            <module name="Magento_Cms"/>
        </sequence>
    </module>
</config>

step 5:/app/code/Customer/Attribute/etc/di.xml

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

</config>

step6:app/design/frontend/vendor/theme/Magento_Customer/templates/form/register.phtml

<div class="field ">
        <label for="custom_field" class="label"><span><?= __('affiliateEmail') ?></span></label>
        <div class="control">
            <input type="text" name="affiliate_email" id="affiliate_email" value="<?= $block->escapeHtml($block->getFormData()->getCustomField()) ?>" title="<?= __('affiliateEmail') ?>" class="input-text" data-validate="{required:false,'validate-email':true}">
        </div>
    </div>

after run below command

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush
  • Hi! What is the table this custom customer registration field saving ? It is not visible in customer entity table. – ashanr Jan 24 at 7:08
  • customer_eav_attribute, eav_entity_attribute – Rakesh Donga Jan 24 at 7:15
  • Thank you! I can see custom field is saving in customer_entity_varchar table . Problem solved – ashanr Jan 24 at 7:24
0

Add Custom field in Customer Registration form Programmatically

Step 1: Create InstallData.php file under app/code/Vendor/Module/Setup directorty and enter below code

<?php 
namespace Vendor\Module\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        if (version_compare($context->getVersion(), '1.0.0') < 0){

                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $customerSetup = $objectManager->create('Vendor\Module\Setup\CustomerSetup');
                $customerSetup->installAttributes($customerSetup);



        }

    }
}

Step 2: Create CustomerSetup.php file under app/code/Vendor/Module/Setup directory and enter below code

<?php 
namespace Vendor\Module\Setup;

use Magento\Eav\Model\Config;
use Magento\Eav\Model\Entity\Setup\Context;
use Magento\Eav\Setup\EavSetup;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory;

class CustomerSetup extends EavSetup {

    protected $eavConfig;

    public function __construct(
        ModuleDataSetupInterface $setup,
        Context $context,
        CacheInterface $cache,
        CollectionFactory $attrGroupCollectionFactory,
        Config $eavConfig
        ) {
        $this -> eavConfig = $eavConfig;
        parent :: __construct($setup, $context, $cache, $attrGroupCollectionFactory);
    } 

    public function installAttributes($customerSetup) {
        $this -> installCustomerAttributes($customerSetup);
        $this -> installCustomerAddressAttributes($customerSetup);
    } 

    public function installCustomerAttributes($customerSetup) {


        $customerSetup -> addAttribute(\Magento\Customer\Model\Customer::ENTITY,
            'token',
            [
            'label' => 'Token',
            'system' => 0,
            'position' => 100,
            'sort_order' =>100,
            'visible' =>  true,
            'note' => '',


                        'type' => 'varchar',
                        'input' => 'text',

            ]
            );

        $customerSetup->getEavConfig()->getAttribute('customer', 'token')->setData('is_user_defined',1)->setData('is_required',0)->setData('default_value','')->setData('used_in_forms', ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout']) -> save();

    } 

    public function installCustomerAddressAttributes($customerSetup) {

    } 

    public function getEavConfig() {
        return $this -> eavConfig;
    } 
}

Step 3: Override frontend layout file in our custom module. Create customer_account_create.xml file under app/code/Vendor/Module/view/frontend/layout directory and enter below code

<?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="content">
            <block class="Magento\Customer\Block\Form\Register" name="customer_form_register" template="Vendor_Module::form/register.phtml">
                <container name="form.additional.info" as="form_additional_info"/>
                <container name="customer.form.register.fields.before" as="form_fields_before" label="Form Fields Before" htmlTag="div" htmlClass="customer-form-before"/>
            </block>
        </referenceContainer>
    </body>
</page>

Step 4: Override customer registration form template file in our custom module to add the custom attribute html. Copy register.phtml file from vendor/magento/module-customer/view/frontend/templates/form directory and paste it under app/code/Vendor/Module/view/frontend/templates/form directory. Enter below lines under the form tag.

 <?php
//add token attribute
<div class="field">
    <label class="label" for="token"><span><?php /* @escapeNotVerified */ echo __('Token') ?></span></label>
    <div class="control">
        <input type="text" name="token">
    </div>
</div>

This will add the token text field in customer registration form. You can change the field whatever you want

I hope this will help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.