Magento 2 Field In address

Magento 2: Create Custom Field In Address Form

In This blog we will try to create a custom field on Customer address and display it in the order creation page .

For creating a field we will target customer_address table and we will add it via eav fields. for our example I will create a email field in shipping and billing address of the customer using upgrade/update schema. the module for my example have the namespace of Gm_Module.

Step 1: Create a upgrade schema

app/code/Gm/Module/Setup
<?php

namespace Gm\Module\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;

class UpgradeSchema implements UpgradeDataInterface {

    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory,Config $eavConfig) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
    }

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


        if (version_compare($context->getVersion(), '1.0.5') < 0){
            /** @var EavSetup $eavSetup */
            $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
            $eavSetup->addAttribute('customer_address', 'email', [
                'type' => 'varchar',
                'input' => 'text',
                'label' => 'Email',
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'system'=> false,
                'group'=> 'General',
                'position' => 160,
                'global' => true,
                'visible_on_front' => true,
            ]);

            $customAttribute =$this->eavConfig->getAttribute('customer_address', 'email');
            $customAttribute->setData(
                'used_in_forms',
                ['adminhtml_customer_address','customer_address_edit','customer_register_address'] //list of forms where you want to display the custom attribute
            );
            $customAttribute->save();


        }
        
        


    }

}

I have added email in billing and shipping address and in customer address form.Once you have placed this schema in schema run setup upgrade command and visit the order page you will see the newly created field in address information in sales order page and in customer address section. Now you can see at the bottom the Email field is availble in customer address.

Leave a Comment

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