Add Custom Field to Customer Address

In this tutorial, we will see how to add custom fields to magento customer address.

In this tutorial we will add a field called ‘Govt ID#’ to address in admin, customer registration form, customer edit address and checkout pages.
Let start step by step, first will create an attribute and show it in admin. The module used by me here is name Excellence_Address. You can download the module createe here
[dm]24[/dm]

Adding Field to Admin

First we need to create the address attribute. There are two ways to do this one is through your module sql file or you can do it through directly through sql query.
First we will see it through the module.
In your module’s config.xml file, add this in the resource tag.

<address_setup>
                <setup>
                    <module>Excellence_Address</module>
                    <class>Mage_Customer_Model_Entity_Setup</class> <!-- This is the important thing-->
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </address_setup>

The important thing is to have your module’s setup class pointed to Mage_Customer_Model_Entity_Setup.
Next in the module’s mysql-install file we will put in the code

$installer = $this;

$installer->startSetup();

$this->addAttribute('customer_address', 'govt_id', array(
	'type' => 'varchar',
	'input' => 'text',
	'label' => 'Govt ID No#',
	'global' => 1,
	'visible' => 1,
	'required' => 0,
	'user_defined' => 1,
	'visible_on_front' => 1
));
Mage::getSingleton('eav/config')
	->getAttribute('customer_address', 'govt_id')
	->setData('used_in_forms', array('customer_register_address','customer_address_edit','adminhtml_customer_address'))
	->save();
$installer->endSetup(); 

This will add the relevant database entries. If you want to do it directly i.e through database or phpmyadmin. Then you need to do the below.
eav_attribute table
insert a row in this table with values entity_type_id = 2, attribute_code = govt_id, backend_type = varchar, fontend_input = text, fontend_label = Govt ID No#, is_user_defined = 1, is_required = 1, default = NULL.
eav_entity_attribute table
insert a row in this table with values entity_type_id = 2,attribute_set_id =2, attribute_group_id = 2, attribute_id = (The attribute_id or the primary key of the row inserted in the eav_attribute table)
customer_eav_attribute table
insert a row in this table with values attribute_id = (The attribute_id or the primary key of the row inserted in the eav_attribute table), is_visible = 1 rest all column will take default values
customer_form_attribute table
1. insert row in this table with values form_code = adminhtml_customer_address and attribute_id = (The attribute_id or the primary key of the row inserted in the eav_attribute table). This required for the attribute to show up in the admin
2. insert row in this table with values form_code = customer_address_edit and attribute_id = (The attribute_id or the primary key of the row inserted in the eav_attribute table). This required for the attribute to get saved in edit address form and checkout page
3. insert row in this table with values form_code = customer_register_address and attribute_id = (The attribute_id or the primary key of the row inserted in the eav_attribute table). This is required to save the attribute in the create account page
After doing this step, you should be able to do see your new address attribute in the admin.

Admin Address Attribute

Admin Address Attribute

Address Format

Next we need to change the address display format, this format is used everywhere in magento where ever address is displayed. To change the format, go to System -> Configuration -> Customer Configuration -> Address Template
There you will see 5 options, we need to change all.
Text
Add {{depend govt_id}}ID# {{var govt_id}}{{/depend}} where ever you want it. {{depend}} basically checks, if govt_id is not empty.
Text One line
Add {{depend govt_id}}ID# {{var govt_id}}{{/depend}} where ever you want it. This format shows up in the checkout page shipping,billing address dropdowns.
HTML
Add {{depend govt_id}}<br/>ID# {{var govt_id}}{{/depend}}. This format is used in many places like Order View, Address Display etc.
PDF
Add {{depend govt_id}}<br/>ID# {{var govt_id}}{{/depend}}|. This format is used in PDF invoices, shipments etc.
Javascript Template
Add <br/>ID#{govt_id}. This is used in admin add/edit address area.
After saving these in the configuration, the new address format should be visible. You can view this here

New Address Format

New Address Format

Create Account Address

First to show address in the magento create account form we need to make changes to customer\form\register.phtml (magento 1.6- version) or persistent\customer\form\register.phtml (magento 1.6+ version). If your using a module we will overwrite these files and make changes, if your not using a module you can make these changes directly. To overwrite, in your module’s layout xml file

<customer_account_create>
    	<reference name='customer_form_register'>
			<action method='setTemplate'><template>address/persistent/customer/form/register.phtml</template></action>
    	</reference>
    </customer_account_create>

Next in the phtml file regsiter.phtml created we will copy the default magento register.phtml contents and add our new field.
First in the beginning of the file add this code, which will show all the address fields.

<?php $this->setShowAddressFields(true);?>

Next we need to add our new field, place this code where you want to show the new field

<li class="fields">
                    <div class="field">
                        <label for="govt_id" class="required"><em>*</em><?php echo $this->__('Govt ID#') ?></label>
                        <div class="input-box">
                            <input type="text" name="govt_id" value="<?php echo $this->htmlEscape($this->getFormData()->getGovtId()) ?>" title="<?php echo $this->__('Govt ID#') ?>" id="govt_id" class="input-text required-entry" />
                        </div>
                    </div>
                </li>

After this the new field added should be automatically saved to the database. You can view the new field in the admin and my account area.

My Account Address Area

My Account Address Area

Edit Address

Next, in the My Account -> Edit Address form we need to add the the new field as well. For this we need to edit the customer\address\edit.phtml file. In the module’s layout xml file put in this code

 <customer_address_form>
    	<reference name='customer_address_edit'>
    		<action method='setTemplate'><template>address/customer/address/edit.phtml</template></action>
    	</reference>
    </customer_address_form>

and in the new edit.phtml file put in the form field where every required

<li class="fields">
                 <div class="field">
                        <label for="govt_id" class="required"><em>*</em><?php echo $this->__('Govt ID#') ?></label>
                        <div class="input-box">
                            <input type="text" name="govt_id" value="<?php echo $this->htmlEscape($this->getAddress()->getGovtId()) ?>" title="<?php echo $this->__('Govt ID#') ?>" id="govt_id" class="input-text required-entry" />
                        </div>
                    </div>
                </li>

Now editing/saving the Govt ID will work.

Checkout Billing/Shipping Step

Now, we will see what we need to do for adding the fields in shipping and billing steps of checkout page.
For this need to make changes to the checkout/onepage/billing.phtml and checkout/onepage/shipping.phtml files. To do this in the module’s layout xml file put in this code

<checkout_onepage_index>
    	<reference name='checkout.onepage.billing'>
    		<action method='setTemplate'><template>address/checkout/onepage/billing.phtml</template></action>
    	</reference>
    	<reference name='checkout.onepage.shipping'>
    		<action method='setTemplate'><template>address/checkout/onepage/shipping.phtml</template></action>
    	</reference>
    </checkout_onepage_index>

Next in the shipping.phtml and billing.phtml files need to add the field. Add this code in billing.phtml file

<li class="fields">
                    <div class="field">
                        <label for="govt_id" class="required"><em>*</em><?php echo $this->__('Govt ID#') ?></label>
                        <div class="input-box">
                            <input type="text" name="billing[govt_id]" value="<?php echo $this->htmlEscape($this->getAddress()->getGovtId()) ?>" title="<?php echo $this->__('Govt ID#') ?>" id="billing:govt_id" class="input-text required-entry" />
                        </div>
                    </div>
                </li>

and add this code in shipping.phtml file

<li class="fields">
	                    <div class="field">
	                        <label for="govt_id" class="required"><em>*</em><?php echo $this->__('Govt ID#') ?></label>
	                        <div class="input-box">
	                            <input type="text" name="shipping[govt_id]" value="<?php echo $this->htmlEscape($this->getAddress()->getGovtId()) ?>" title="<?php echo $this->__('Govt ID#') ?>" id="shipping:govt_id" class="input-text required-entry" />
	                        </div>
	                    </div>
	                </li>

Next, we need to add this xml code to our module config.xml file

<global>
        <fieldsets>
        	<sales_convert_quote_address>
        		<govt_id>
                    <to_order_address>*</to_order_address>
                    <to_customer_address>*</to_customer_address>
                </govt_id>
        	</sales_convert_quote_address>
        	<customer_address>
        		<govt_id>
                    <to_quote_address>*</to_quote_address>
                </govt_id>
        	</customer_address>
        </fieldsets>
    </global>

Next we need to add govt_id column in the tables sales_flat_order_address, sales_flat_quote_address. To do this in your module’s sql file

$tablequote = $this->getTable('sales/quote_address');
$installer->run("
ALTER TABLE  $tablequote ADD  `govt_id` varchar(255) NOT NULL
");

$tablequote = $this->getTable('sales/order_address');
$installer->run("
ALTER TABLE  $tablequote ADD  `govt_id` varchar(255) NOT NULL
");

Now, if a new address is created from the checkout step the new field will be added to the database and show up the order view.

These are all the places where the address shows up. The new field we have added will automatically show up in emails, pdfs etc.
  • duzenz

    excellent post thanks

  • Pete

    Thank you very much! I dont know how many hours i tried to figure out how to add an address attribute correctly… Thanks!

  • Dani

    how can i do this thing with more fields for example i want to add 5 fields…. 🙂

    • Manish Prakash

      Please understand the tutorial in detail. Its very simple to add more fields but i cannot explain that in a comment.

  • Dani

    can u explain it in my e-mail [email protected] please it is important

  • Oğuz Çelikdemir

    Dear Manis,
    the article request system does not working right now which isn’t send email, please check.

  • Hi,

    Great tutorial ! I can’t get the data to save to the database ? i have checked the database and the tables seem to be correct. Using your code from site ?  can you suggest where i may be going wrong … thanks wayne 

    • Manish Prakash

      Once you can try clearing the magento cache

      i.e Flush Magento Cache and Flush Cache Storage

      • Manish tried that no luck, I can enter and save to db through the edit customer in backend but does not save through input form ? also do i need to have class Mage_Customer_Resource_Setup in my config file as i’m using mage 1.6.1 ? thanks wayne 

        • Sorted it now, had module overiding the form ! thanks for the great tutorial !! wayne 

          •  Hi Wayne, Please help me,  I have same problem, would be nice if you help me a.s.a.p.
            Pls email me: [email protected]
            Thanks!

          • Visakh Viswanath

            Hello Wayne,

            Could you please explain how you sorted this issue, because i am also stuck at this point. Thanks. ([email protected])

  • Ivan Freire

    Sorry, I’m newbie on Magento and sure the anwer is easy but I don’t know it. I downloaded the code and tried to install it using connect manager but I couldn’t. It told me several thing like date incorrect, name incorrect etc etc.
    I was searching and I know that zip don’t have a package.xml file but I don’t know why. How can I install this code in my magento dev installation?

    • Manish Prakash

      You need to directly update the module using ftp. You don’t have to use magento connect. Just upload the downloaded file as per the folder structure in the zip file.

  • Very useful stuff. I really enjoy reading your post.
    Thanks

    • Manish Prakash

      Thanks Daniel.

  • Raj

    I added one new field but it not shows on backend Sales -> Order -> Create New Order -> Create New Customer in Billing and Shipping address form.

    Pls Help me..

  • Gagandeeps

    I am getting the field in frontend and backend , correct.

    But i wanted it to be in select tag , i tried changing the attribute from backend from tewxt to select , but it was showing me the error

    Actually i have made my custom module for counties under cities and i need to use the counties to modify the shipping address

    So the client wants the counties and cities in drop down

    So can you please help to get me it converted from text to select?

    Thanks in advance

  • Alin

    it’s an awsome post, it helped me understand how magento goes about customer attributes. 
    however, i can’t figure how to to get this working  “Now, if a new address is created from the checkout step the new field will be added to the database and show up the order view” if i added the attribute manualy to the database and .phtml files. how can i make it save data in the field to the database if a new account is created at checkout?  *(this is for a secondary field added manualy, i also have your extension installed). Thank you in advance!

  • Alin

    It’s a great tutorial, i managed to add a second customer field by “duplicating” your extension, but i did not manage to add two field to the setup installer. can this be done? or it needs a different approach?

  • I spent a lot of time to understand how to add custom attribute to customer address. Helped me to your tutorial. Thank you very much.

    • This tutorial would be perfect if it would be contain an example additional field checkbox

      • Manish Prakash

        Hi, eprinc
        Thankyou for your feedback , i will try to make the mentioned changes in the tutorial.

  • Sugnaram

    i add a one new field using your extension. it’s working fine but i want to add one more what should i do like (govt_id2) i change in four files like(edit.phtml,register.phtml,config.xml,mysql4-install-0.1.0.php) but not displaying in backed. what should i do more for that PLZ ……..

  • Sugnaram

    your tutorial is very good for add one field but i want to add more fields how can i do plz help me advance thanks
    i added in mysql query field is it right or not(startSetup();

    $this->addAttribute(‘customer_address’, ‘govt_id’, array(
        ‘type’ => ‘varchar’,
        ‘input’ => ‘text’,
        ‘label’ => ‘Govt ID NO#’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 0,
        ‘user_defined’ => 1,
        ‘visible_on_front’ => 1
    ), ‘govt_id2’, array(
        ‘type’ => ‘varchar’,
        ‘input’ => ‘text’,
        ‘label’ => ‘Govt ID2 NO#’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 0,
        ‘user_defined’ => 1,
        ‘visible_on_front’ => 1
    ));

    if (version_compare(Mage::getVersion(), ‘1.6.0’, ‘getResource()->getEntityType()->getDefaultAttributeSetId();
        $this->addAttributeToSet(‘customer_address’, $attrSetId, ‘General’, ‘govt_id’,’govt_id2′);
    }

    if (version_compare(Mage::getVersion(), ‘1.4.2’, ‘>=’))
    {
        Mage::getSingleton(‘eav/config’)
        ->getAttribute(‘customer_address’, ‘govt_id’,’govt_id2′)
        ->setData(‘used_in_forms’, array(‘customer_register_address’,’customer_address_edit’,’adminhtml_customer_address’))
        ->save();
    }

    $tablequote = $this->getTable(‘sales/quote_address’);
    $installer->run(”
    ALTER TABLE  $tablequote ADD  `govt_id` varchar(255) NOT NULL, ADD `govt_id2` varchar(255) NOT NULL
    “);

    $tablequote = $this->getTable(‘sales/order_address’);
    $installer->run(”
    ALTER TABLE  $tablequote ADD  `govt_id` varchar(255) NOT NULL, ADD `govt_id2` varchar(255) NOT NULL
    “);
    my second field is govt_id2 same as in cofig .xml copy fields and rename one more but not working and not displaying error advance thanks for help
    $installer->endSetup(); ) 

  • Manish Prakash

    This module will work on 1.5+ only I think

  • veeresh sabanna

    Hello Manish Prakash

    Here I need to upload a address using csv files and that content has to store in database, so how can I do this in magento, can you please help me about this issue,

    Regards,
    Veeresh Sabanna

  • Magento Modules

    did you figure it out

  • Thushara Mannaperuma

    This works fine. Thank you Manish. Can you explain how to add a select type attribute here instead of the
    text type.

  • carlosalvet

    Perfect tutorial! is great, just the example has a little problems, in design it is write “fontend” in case of “frontend”, and shipping.phtml and billing.phtml throws error, if you write it again from the original files, the problem is resolved. The tutorial very good!!!! thanks!

  • Rupa

    I have no idea what i did wrong. I altered part of the info so that it asks for an email address instead on a ID#. You can enter the email address, but it won’t store into the system. Definitely need a little help 😐

  • Can u please show us how to create a select type(dropdown) customer address attribute. Where we can set the select options? Thank you.

  • carlosalvet

    Hi, is perfect your post, I relly like your blog, I installed this module in my store with changes, i add 3 fields on customer address account, 3 numeric fields. The problem is the last field in shipping place. When I am in the customer information into the admin, this field is shown a false number, ever the same false number in all cases with error, but the e-mail is received correct, with the same number as the user typed. By the same way the number appears wrong the next times, in db is corrupt. This don’t occure with the billing 3th field.

    Can you help me? I don’t know where i can start to find the problem to fix.

  • It works excelent in magento 1.7.0.2 for more than one field 😀

  • GiedriusKK

    can anyone send me this extension? for me it doesnt work 🙁 please, [email protected]
    magento 1.7.0

  • Manish Prakash

    Thanks sharanya.

  • Lighthouse Nguyen

    it works excellent in 1.7.0.2, but one problem is the value can’t show in checkout billing info step, when i click continue button then appearred a popup with a notice “custom field is required”. I have tried click dropdown to select “New Address” then i see the custom field is empty, it has to have a value similar in edit address form or in admin edit address form.

  • rahul dadhich

    How to change Sort order in admin pannel.

    I want govt ID# is come just after Company and before Street Address., plz help me.

  • Shivam

    hi Manish

    I am using Mage-world one step checkout page , problem is the govt_id value not showing in checkout billing info step , It’s showing customer address filed . Plz help

  • Luc van Folmert

    I end up with error “Call to a member function setData() on a non-object” when entering Address Book – what could possibly go wrong?

  • sheetal

    Hi Manish,
    I need to create dropdwon instead of text box. Its giving me error ”

    Source model “” not found for attribute “newzip” please tell me where I can create it.
    I have created below code in Model->Entity->Newzip.php
    class Excellencesbnew_Address_Model_Attribute_Source_Newzip extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
    {
    public function getAllOptions()
    {
    if ($this->_options === null) {
    $this->_options = array();
    $this->_options[] = array(
    ‘value’ => ”,
    ‘label’ => ‘Choose Option..’
    );
    $this->_options[] = array(
    ‘value’ => ‘sw1’,
    ‘label’ => ‘sw1’
    );
    $this->_options[] = array(
    ‘value’ => ‘sw2’,
    ‘label’ => ‘sw2’
    );
    $this->_options[] = array(
    ‘value’ => ‘sw3’,
    ‘label’ => ‘sw3’
    );

    }

    return $this->_options;
    }
    }

    and also defined in installer ‘source’ => ‘address/entity_newzip’,
    Please guide me how can i resolve the issue. Its very urgent. I will be very grateful if you help me.

  • Marco

    Thanks! it works great even in Magento 1.9!
    But how do I modify mysql install file if I want to put two fields?
    Thanks a lot!!

  • most historians produce quite horrible stories. As a result, you could have a plus on the get-go considering people teachers will probably be absolved to not at any time perhaps become learning throw away after you perhaps produce obviously…

  • Lorenzo Sfarra

    Can someone please share the source code? The link is not active anymore.

  • College composition publishing versus. college composition publishing you will find several variances in between some along with good Prof., generally how the degrees may possibly decline and also this this specific tasks along with publishing are going to be much more hard plus much more time-consuming….

  • kode eshwaran

    Hi I am Kodeeshwaran
    My new field(govt id) is not added in the customer address in admin panel.
    I m using both ways(using coding/ directly add the field in database).
    Not show in the admin panel.I am using magento 1.9.1.Please help me to add new field in customer address.

  • Marco

    Hi, I’ve tested it in magento 1.9, works great, but if I pay with paypal express I can see the field in the /paypal/express/review/ page, then I submit order but the custom field is not stored in database… should I change config.xml so that the value is stored even with this paymant method?

    Thanks

    sales_convert_quote_address

    • Fabrizio Vanzani

      Marco, I have the same problem. Did you solve it?

      • Hi, To save extra fields in paypal express payment you need to change the template file for paypal express in /app/design/frontend/your_theme/default/template/paypal/express/review/address.phtml

        Hope this helps

  • Takashi

    Awesome post! Thank you! Working fine in 1.9.1

  • ahmed beshir

    I Have A problem with the first part this is the error ‘Source model “” not found for attribute “area”‘

  • ebinezer anandharaj

    i used this code. its working in admin panel. but not working in front panel.

  • can you guide me for magento 2?

  • Sanjay Vaghela

    Hi Manish,

    Download link is now working. so how can i get code?

    Thank you.

  • Piyush Dangre

    Can anyone guide for Magento 2?

  • Pradeep Singh

    Excellent post

  • sagar panchal

    perfect!!! working around from last three days!!! thanx alot man!!! good job!!! 🙂