Add Custom Fields to Customer Account – Magento 1.7

Banners
In this blog post, we are going to see how to add new fields to customer account pages i.e registration,edit profile, checkout and admin manage customer.

In this blog will look at magento version 1.4.2(+) and 1.4.2(-) and how to add fields in different magento version.In magento 1.4.2 version, major changes were made in account management system, so we will look at both versions. It would be better to create a magento module for this purpose, but it is not necessary. Attached is the source files of magento module created.
Module also tested on Latest 1.7.0.2
Module Name: Customer Profile Add Fields Source


So lets start of, as an example will we add a drop down field called School in Customer Profile. The below codes are written only for 1 field, if you want to add multiple fields then you need to repeat the below for multiple attributes.

Step1: Create Attribute

So first we need to create a custom attribute called School.
If you have a magento module
If you have created a module, then in your mysql_install or mysql_upgrade files, you need to put in this code

<?php
$installer = $this;
$installer->startSetup();
$setup = Mage::getModel('customer/entity_setup', 'core_setup');
$setup->addAttribute('customer', 'school', array(
	'type' => 'int',
	'input' => 'select',
	'label' => 'School',
	'global' => 1,
	'visible' => 1,
	'required' => 0,
	'user_defined' => 1,
	'default' => '0',
	'visible_on_front' => 1,
        'source'=> 'profile/entity_school',
));
if (version_compare(Mage::getVersion(), '1.6.0', '<='))
{
      $customer = Mage::getModel('customer/customer');
      $attrSetId = $customer->getResource()->getEntityType()->getDefaultAttributeSetId();
      $setup->addAttributeToSet('customer', $attrSetId, 'General', 'school');
}
if (version_compare(Mage::getVersion(), '1.4.2', '>='))
{
	Mage::getSingleton('eav/config')
	->getAttribute('customer', 'school')
	->setData('used_in_forms', array('adminhtml_customer','customer_account_create','customer_account_edit','checkout_register'))
	->save();
}
$installer->endSetup();

and in your config.xml file

<profile_setup> <!-- Replace with your module name -->
 <setup>
  <module>Excellence_Profile</module> <!-- Replace with your module name -->
  <class>Mage_Customer_Model_Entity_Setup</class>
 </setup>
</profile_setup>

Note: Name of my module is Excellence_Profile
If you don’t have a module
In this case you do this

$setup = Mage::getModel('customer/entity_setup');
$setup->addAttribute('customer', 'school', array(
	'type' => 'int',
	'input' => 'select',
	'label' => 'School',
	'global' => 1,
	'visible' => 1,
	'required' => 0,
	'user_defined' => 1,
	'default' => '0',
	'visible_on_front' => 1,
        'source' => 'profile/entity_school',
));
if (version_compare(Mage::getVersion(), '1.6.0', '<='))
{
      $customer = Mage::getModel('customer/customer');
      $attrSetId = $customer->getResource()->getEntityType()->getDefaultAttributeSetId();
      $setup->addAttributeToSet('customer', $attrSetId, 'General', 'school');
}
if (version_compare(Mage::getVersion(), '1.4.2', '>='))
{
	Mage::getSingleton('eav/config')
	->getAttribute('customer', 'school')
	->setData('used_in_forms', array('adminhtml_customer','customer_account_create','customer_account_edit','checkout_register'))
	->save();
}

you need to place the above code in some phtml file, and run it only once. Remove the code once this code has run.
To check if this step is successful, open your database in phpmyadmin. Go to table ‘eav_attribute’ and search for the attribute code ‘school’ or whatever is the code of your attribute. If there is no entry for this attribute it means the above code was not executed. To fix, go to table ‘core_resource’, find the entry of your module there. You need to delete that entry so that the sql is executed.

Step2: Source Model

Since we are using a dropdown attribute, we need to tell magento where to look for the drop down options. This is where the source model comes into picture, in our case we have mentioned source_model as ‘profile/entity_school’
If you are using text attribute, just keep source_model as blank and skip this section
So our code for the source model would be

<?php
class Excellence_Profile_Model_Entity_School 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' => 1,
                    'label' => 'School1'
			);
			$this->_options[] = array(
                    'value' => 2,
                    'label' => 'School2'
			);
			$this->_options[] = array(
                    'value' => 3,
                    'label' => 'School3'
			);
			
		}

		return $this->_options;
	}
}

This code is simpe, the getAllOptions() return the array with all our drop down options. If you want to fetch options, from database table, you can put a db query here as well.
By end of this step, you should see your attribute in the Admin -> Manage Customer -> Edit Customer section. If not, there is something wrong, you need to follow the Explanation at end of blog post.

Step3: Registration Form

Here we will add our attribute, to the customer registration form. In version 1.6.0(+) the phtml file used is persistance/customer/register.phtml and in version 1.6.0(-) the phtml file used is customer/form/register.phtml
So we need to open the phtml file, based on magento version and add this code in the <form> tag.

<li>
            	 	<?php 
            	 		$attribute = Mage::getModel('eav/config')->getAttribute('customer','school');
            	 	?>
                    <label for="school" class="<?php if($attribute->getIsRequired() == true){?>required<?php } ?>"><?php if($attribute->getIsRequired() == true){?><em>*</em><?php } ?><?php echo $this->__('School') ?></label>
                    <div class="input-box">
                        <select name="school" id="school" class="<?php if($attribute->getIsRequired() == true){?>required-entry<?php } ?>">
                        	<?php
                        		 $options = $attribute->getSource()->getAllOptions();
                        		 foreach($options as $option){
                        	?>
                        		<option value='<?php echo $option['value']?>' <?php if($this->getFormData()->getSchool() == $option['value']){ echo 'selected="selected"';}?>><?php echo $this->__($option['label'])?></option>
                        	<?php } ?>
                        </select>
                    </div>
                </li>		

For magento 1.4.2(+) that is all that is required for the registration step. If you create a user from here, you should see the selected drop down value in admin.
For magento 1.4.1(-), we need to do another thing open the your modules config.xml file and add

<global>
        <fieldsets>
            <customer_account>
                 <school><create>1</create><update>1</update><name>1</name></school>
            </customer_account>
        </fieldsets>
</global>
Step4: Edit Account Information

Once, user has created his account in the MyAccount->Account Information section he should be able to edit the school field as well. For this open the phtml file customer/form/edit.phtml and put in the code in the <form>

<?php 
            	 		<li>
            	 	<?php 
            	 		$attribute = Mage::getModel('eav/config')->getAttribute('customer','school');
            	 	?>
                    <label for="is_active" class="<?php if($attribute->getIsRequired() == true){?>required<?php } ?>"><?php if($attribute->getIsRequired() == true){?><em>*</em><?php } ?><?php echo $this->__('School') ?></label>
                    <div class="input-box">
                        <select name="school" id="school" class="<?php if($attribute->getIsRequired() == true){?>required-entry<?php } ?>">
                        	<?php
                        		 $options = $attribute->getSource()->getAllOptions();
                        		 foreach($options as $option){
                        	?>
                        		<option value='<?php echo $option['value']?>' <?php if($this->getCustomer()->getSchool() == $option['value']){ echo 'selected="selected"';}?>><?php echo $this->__($option['label'])?></option>
                        	<?php } ?>
                        </select>
                    </div>
                </li>	

Now, you the account information editing should be working.

Step5: Checkout Page Registration

A registration form also shows up at the checkout page in magento. To add you field here, you need to edit checkout/onepage/billing.phtml for magento version 1.6(-) and persistant/checkout/onepage/billing.phtml for magento version 1.6(+) file and then find the code

 <?php if(!$this->isCustomerLoggedIn()): ?>

inside this if condition add your field

<li>
            	 	<li>
            	 	<?php 
            	 		$attribute = Mage::getModel('eav/config')->getAttribute('customer','school');
            	 	?>
                    <label for="school" class="<?php if($attribute->getIsRequired() == true){?>required<?php } ?>"><?php if($attribute->getIsRequired() == true){?><em>*</em><?php } ?><?php echo $this->__('School') ?></label>
                    <div class="input-box">
                        <select name="billing[school]" id="school" class="<?php if($attribute->getIsRequired() == true){?>required-entry<?php } ?>">
                        	<?php
                        		 $options = $attribute->getSource()->getAllOptions();
                        		 foreach($options as $option){
                        	?>
                        		<option value='<?php echo $option['value']?>'><?php echo $this->__($option['label'])?></option>
                        	<?php } ?>
                        </select>
                    </div>
                </li>

Next open your module config.xml or any other config.xml file, add the following lines

<global>
	 <fieldsets>
	   <checkout_onepage_quote>
	   	 <customer_school>
		     <to_customer>school</to_customer>
	     </customer_school>
	   </checkout_onepage_quote>
		<customer_account>
			<school>
				<to_quote>customer_school</to_quote>
			</school>
		</customer_account>	   
	  </fieldsets>
	</global>

Next we need to make some changes in the quote table i.e sales_flat_quote table in magento. If you have a module then create an upgrade version of your sql file and put in this code

$tablequote = $this->getTable('sales/quote');
$installer->run("
ALTER TABLE  $tablequote ADD  `customer_school` INT NOT NULL
");

or if you don’t have a module, then just execute this query in phpmyadmin.

ALTER TABLE  `sales_flat_quote` ADD  `customer_school` INT NOT NULL

After doing this make sure to clear you magento cache, specifically “Flush Magento Cache” and “Flush Cache Storage”.
Now when you place order, the customer is created with the correct school attribute.

Detailed Explanation’s of Steps

The first step is creating an customer attribute. So there are the actual sql queries that get executed, through our code.
First entry it made in the eav_attribute table

INSERT INTO  `eav_attribute` (
`attribute_id` ,
`entity_type_id` ,
`attribute_code` ,
`attribute_model` ,
`backend_model` ,
`backend_type` ,
`backend_table` ,
`frontend_model` ,
`frontend_input` ,
`frontend_label` ,
`frontend_class` ,
`source_model` ,
`is_required` ,
`is_user_defined` ,
`default_value` ,
`is_unique` ,
`note`
)
VALUES (
NULL ,  '1',  'school', NULL , NULL ,  'int', NULL , NULL ,  'select',  'School', NULL ,  'profile/entity_school',  '1',  '0',  '0',  '0',  ''
);

EAV Attribute DB Entry

EAV Attribute DB Entry


After insert query, the attribute generated is my case is 121. Next this attribute needs to be associated to an attribute set, the sql for this is

INSERT INTO  `eav_entity_attribute` (
`entity_attribute_id` ,
`entity_type_id` ,
`attribute_set_id` ,
`attribute_group_id` ,
`attribute_id` ,
`sort_order`
)
VALUES (
NULL ,  '1',  '1',  '1',  '121',  '0'
);
The sort_order value in this table, specifies where the attribute will show in admin.

DB Entry

DB Entry


Next we need to make entry in a table “customer_eav_attribute”

INSERT INTO  `customer_eav_attribute` (
`attribute_id` ,
`is_visible` ,
`input_filter` ,
`multiline_count` ,
`validate_rules` ,
`is_system` ,
`sort_order` ,
`data_model`
)
VALUES (
'121',  '1', NULL ,  '1', NULL ,  '0',  '0', NULL
);

If your using multiple store, you need to make an entry in customer_eav_attribute_website as well, but this entry is not compulsary

INSERT INTO `customer_eav_attribute_website` (
`attribute_id` ,
`website_id` ,
`is_visible` ,
`is_required` ,
`default_value` ,
`multiline_count`
)
VALUES (
'121',  '0',  '1',  '0', NULL , NULL
);

Next we need to make entry in a table called “customer_form_attribute”

INSERT INTO  `customer_form_attribute` (
`form_code` ,
`attribute_id`
)
VALUES (
'adminhtml_customer',  '121'
), (
'checkout_register',  '121'
), (
'customer_account_create',  '121'
), (
'customer_account_edit',  '121'
)
;

Now, if you open magento Admin -> Manage Customers -> Edit Customer, you should be able to see your new attribute in admin.

Adding Multiple Fields

In this section we will see what all changes we need to do in order to add multiple fields to the user profile.

  • First we need to create multiple attributes in database. The create attribute Step1 needs to be repeated for all the attributes which you have. Right now i have done it only for school attribute, but it needs to be done for all attributes you want to add.
  • Ofcouse you need to have different source model’s if you have different drop down attributes. If you don’t have drop down attributes, you don’t need this.
  • The Step3: Registration step , Step4: Edit Account Information and Step5: Checkout Page , we need to change the phtml code to include all our attributes.
  • The entries made in the xml files for customer_account, checkout_onepage_quote fieldsets, needs to be made for all the attributes.
  • In the sales_flat_quote table we need to add columns for each of our attirbutes. Column name would be same as attribute code.

These are the steps required.

  • Anonymous

    Sir,
    This is muthu kumar.Kindly give me the full path for where can i modify the pages

  • Manish Prakash

    Sorry, which file? please let me know which file are you taking about? which pages you want to modify

  • Manish Prakash

    which method are you using? have you created a module or ur not creating a module?

  • Anonymous

    $setup = Mage::getModel(‘customer/entity_setup’);$setup->addAttribute(‘customer’, ‘school’, array(    ‘type’ => ‘int’,    ‘input’ => ‘select’,    ‘label’ => ‘School’,    ‘global’ => 1,    ‘visible’ => 1,    ‘required’ => 0,    ‘user_defined’ => 1,    ‘default’ => ’0′,    ‘visible_on_front’ => 1,        ‘source’ => ‘profile/entity_school’,));if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();      $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘school’);}if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’)){    Mage::getSingleton(‘eav/config’)    ->getAttribute(‘customer’, ‘school’)    ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))    ->save();}Where shall i put this code sir
     

    • Manish Prakash

      Ok, place this code in appdesignfrontendbasedefaulttemplatepersistentcustomerformlogin.phtml  and then open the login page once.
      All database entries should be made for you. Make sure you cache is turned off from Admin -> System -> Cache Management.

      Also to check if database entries are made check the ‘eav_attribute’ table and see if your attribute code is there in this table.

      • Anonymous

        Sir i have done thatmanually in mysql database and how can i place textbox code in register.phtml.Above you have mentioned for select box.I want this for text box sir

  • Anonymous

    I don’t know i am using magento 1.6.0.0 new installation only sir
     

  • Anonymous

    I didn’t any module for customer sir

  • Anonymous

    I want only customer information like customer name and customer registration number and etc below personal information and i want to edit it when i logged in as customer and when i login as admin i have to see the company details

    • Manish Prakash

      Yes, the blog is written exactly for this only. In this blog, only 1 customer attribute has been explain. since you want two attributes, you need to do all these steps for 2 attributes. 

  • Anonymous

    For text field how can i mention in register.phtml . Please give the full code like selectbox above

    • Manish Prakash

      This would be code for  text field

                          getAttribute(‘customer’,’school’);                    ?>                    <label for="school" class="getIsRequired() == true){?>required”>getIsRequired() == true){?>*__(‘School’) ?>                    School: <input name="school" id="school" class="getIsRequired() == true){?>required-entry” value=’getFormData()->getSchool() ?>’ />                                   

  • Anonymous

    Sir you tell me to insert his code in login.phtml

     $setup =
    Mage::getModel(‘customer/entity_setup’);$setup->addAttribute(‘customer’,
    ‘school’, array(    ‘type’ => ‘int’,    ‘input’ =>
    ‘select’,    ‘label’ => ‘School’,    ‘global’ => 1,    ‘visible’
    => 1,    ‘required’ => 0,    ‘user_defined’ => 1,    ‘default’
    => ’0′,    ‘visible_on_front’ => 1,        ‘source’ =>
    ‘profile/entity_school’,));if (version_compare(Mage::getVersion(),
    ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();      $setup->addAttributeToSet(‘customer’,
    $attrSetId, ‘General’, ‘school’);}if
    (version_compare(Mage::getVersion(), ’1.4.2′,
    ‘>=’)){    Mage::getSingleton(‘eav/config’)    ->getAttribute(‘customer’,
    ‘school’)    ->setData(‘used_in_forms’,
    array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))    ->save();

    But when i changed the code for text field and disable the cache and upload the file and run it.There is no record found in the mysql eav_attribute table .But i manually insert the values in the table.Is it any problem that i manually insert the values

    • Manish Prakash

      No, you can insert values in table manually as well. but you have to make entries in 4 tables, did you do that?

      If your entries are successful then you should be able to see your attribute in admin -> manage customers

      • Anonymous

         I did only adding entry in eav_attribute only

      • Anonymous

        Which are the tables and what are the entries sir.If you told me i will manually insert it sir

  • Anonymous

    sir what is attribute id My attribute id is 926 in eav_attribute.Buth i have not seen in another 4 tables via clicking on attributeid image link in mysql tables.But you told that the attribute id is 121.I have changed the id to 121 and i have inserted the textbox code in register.phtml also but i didn’t any any textbox in frontend and backend also there is no companyname field

    • Manish Prakash

      121 was just an example taken by me. 121 was the attribute id generated for me.  

    • Manish Prakash

      First check your admin Admin -> Manage Customer -> Create Customer, did you get your field there?

      If not, then your database entries are not correct. 

      • Anonymous

         I checked in that also i didn’t get the attribute.and also on my frontend i didn’t get it

  • Anonymous

    Hello manishiitg,

    I’ve been following your manual on how to add a new attribute to a customer, and all is working correctly, but I am unable to change the value of the added attribute from the edit form (this is a simple text attriburte). Both register and checkout forms are working correctly, but they use different methods of passing data. Is there anything that needs to be changed in the controllers maybe? I’m using magento 1.5.1.0

    • Manish Prakash

      Please check your attribute in the eav_attribute table.

      Then go to customer_form_attribute table and check for your attribute id, if the entry for customer_account_edit is there or not?

      Also which version of magento are you using?

      No changes are required in Controller, only database changes are required.

      • Anonymous

        Thanks for the fast reply Manish,

        I’ve checked for the attribute in the customer_form_attribute table, and create_account_edit is there, as well as adminhtml_customer, checkout_register and customer_account_create for this particular attribute_id. I’m using Magento version 1.5.1.0

        • Manish Prakash

          Ok to debug this open your Mage_Customer_AccountController and in the editPostAction() you will see this line
          $customerData = $customerForm->extractData($this->getRequest());

          please print_r($customerData); and paste it here.

          • Anonymous

            Maybe I should point out that this new attribute is found in my account/address book/contact information. Is this method used to change passwords? What is the method used to handle edit address?

          • Manish Prakash

            In that case you need to make changes in Mage_Customer_AddressController in the formPostAction() action.

            you need to do this

            find the line
            $customer = $this->_getSession()->getCustomer();
            after this add
            $customer = $this->_getSession()->getCustomer();
            $customer->setYourAttribute($this->getRequest()->getPost(‘your_attribute’));
            $customer->save();

            this should make it work hopefully. 

          • Anonymous

            Yes! It is working! Thank you very much for the help Manish, and sorry if I’ve spent too much of Your time!

          • Manish Prakash

            No problem at all :)

            Try to share this blog and spread the word :)

  • Anonymous

    Sir i have placed the $setup = Mage::getModel(‘customer/entity_setup’);
    $setup->addAttribute(‘customer’, ‘companyname’, array(
        ‘type’ => ‘varchar’,
        ‘input’ => ‘text’,
        ‘label’ => ‘Company Name’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 1,
        ‘user_defined’ => 0,
        ‘default’ => ’0′,
        ‘visible_on_front’ => 0,
            ‘source’ => ”,
    ));
    if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();
          $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘companyname’);
    }
    if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’))
    {
        Mage::getSingleton(‘eav/config’)
        ->getAttribute(‘customer’, ‘companyname’)
        ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))
        ->save();
    }

    in login.phtml.But the page comes blank when i run

    Please help me

    Thanks in advance

    • Manish Prakash

      I have added source code of the module to this blog post, please download that. it may be helpful to you.

  • Anonymous

    r u there sur

  • http://twitter.com/rogeneiancarino Rogene Ian Carino

    Sir, by using this code i got an “error in request”,please can you help me with thisi follow all instruction above,i downloaded your code,but still it’s not working with me,

    • Manish Prakash

      Hello,

      can you let me know which magento version your are using.
      and where do you get the error in request? which URL or in which action you perform?

      can you send a screen shot of the error?

  • Kasper

    Hello Manish,
    Very interesting tutorial, it is working for me.
    Now I want to be able to access the customer attributes in another module which adjust the final price based upon the custom customer attribute values.
    Can you tell me how I can get the values of the custom attributes?

    • Manish Prakash

      It would be very simple. Just create the custom object
      $customer = Mage::getModel(‘customer/customer’)->load($id);
      echo $custom->getData(‘attribute_code’);

  • Mohan

    Source model “” not found for attribute “custype””;i:1;s:2828:”#0 /var/www/magento/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php(387): Mage::exception(‘Mage_Eav’, ‘Source model “”…’) this error has been coming wen i inserted custype column in to table…

    please send me the solution to my problem

    • Manish Prakash

      This problem comes when in the eav_attribute table, for the attribute code ‘custype’ you have inserted blank in the source_model column. You should insert NULL value in that column rather than blank.

  • http://twitter.com/Bhagyashree5 Bhagyashree Worlikar

    Hello, Manish Sir

          I am using Magento 1.6.0.0. I do not have module I follow the step 1 and i put the code in the following file “C:wampwwwmagentoappdesignfrontendXXXXXXtemplatepersistentcustomerformlogin.phtml”
    when i run the login.phtml file i got the following error.

    “Fatal error: Call to a member function select() on a non-object in C:wampwwwmagentoappcodecoreMageCoreModelResourceSetup.php on line 734 ”

    As I am new to magento not able to solve this error please help me to resolve this error.

    Thanks :)

    • Joe

      Need to use this to get the model:

      $setup = Mage::getModel(‘customer/entity_setup’, ‘core_setup’);

  • Alin Sala

    cand i add multiple attributes at once in mysql_setup? how do i do this? can you point out an example please? thank you!

    • Manish Prakash

      Since this a popular require, I will add a list of steps to this in the existing blog today.

      Thanks

    • Manish Prakash

      I have added a new section to the blog.

  • abiral shakya

    Hello, very nice tutorial, worked like a charm. I wonder what i would have to do to make this into a customer address attribute rather than just the customer attribute. Could you please help me on this.
    Thank you in advance

    • Manish Prakash

      Well I will write a separate tutorial on this. Its not a small thing to explain in comment J

      • abiral shakya

        When will we be able to see this tutorial. any plans.I’m working on it too. Hope to see it soon

        • Manish Prakash

          Well I have added it to my tutorial queue J

  • Foxwo79

    I followed these steps, but changed it from a select to a text input. This included changing the ‘backend_type’ to varchar and ‘frontend_input’ to text. However, when I use $customer->getSchool() it just returns 0. It seems like something is still trying to force it to be an integer. The edit form and admin section still work and display the school text properly. Any ideas why I can’t return the school text?

    • Manish Prakash

      No sure what your doing wrong. After making the changes in database, did you clear all cache in magento?

  • Colemannie

    This is absolutely wonderful, and the only instructions I could get to work in 1.6.  I’m wondering how I can modify this script to be checkboxes.  For instance, I want to ask my customers what kind of needlework they do, and have them be able to check all that apply including knitting, crocheting, and weaving. Any help would be appreciated!  Thanks, Annie

  • Sam

    Nice tutorial! Worked for me just fine. But how do I extend the validate() function in order to gain server side validation for my custom field?
    Thanks in advance!

    • Manish Prakash

      Which validate function? The customer account validate? You need to override that model and put in your custom validation.

      • Sam

        …and I did. Removing validation rules worked fine in the overridden model but my custom rules didn’t affect the form. Which piece of code does connect the custom field to the customer validate() function? Sorry for bothering you again!

        • Manish Prakash

          Not sure I understand your question. Which validation rules you want to put in?

  • Emerson Herzeg

    I can also add file field?

  • http://twitter.com/WayneMarler Wayne Marler

    Manish I have followed most of your module tutorials i think they are the best out there…

    I have followed this tutorial and have added a text input field as well as the select field everything works fine except the text field will not save to the db during the onepage checkout ? the db entries are all ok as i can enter and save the data in the text input field during  the registration process and can save an input through the admin back-end.

    this is the input form in billing.phtm:

                                                *__(‘Childs Name’) ?>                                                    <input type="text" name="billing[childname]" value="htmlEscape($this->getQuote()->getChildname()) ?>” title=”__(‘Childs Name’) ?>” class=”input-text required-entry” id=”billing:childname” />                                           

    I have played about with the input form a tried various things but it will not save to the db ?

    Can you help with this as this is the method i would like use for custom fields.

    Many thanks

    Wayne 

  • Neman

    after make all changes to make it text box instead of drop down
    i got this error Call to a member function getSchool() on a non-object

  • Max

    Fantastic, will try this out later this evening. In regards to enabling all of the default Address fields on the registration, how do I go about doing this? I have tried removing the “getShowAddressFields()): ?>”  with no luck. Can anyone shed any light on this? Thanks

    • Manish Prakash

      To do this in the first line of file customer/form/register.phtml put in this code
      setShowAddressFields(true); ?>

      • Max

        Thanks for your reply. I tried this, cleared the cache and they are unfortunately still not showing. I am using v1.61 if that makes any difference?

      • Max

        Nevermind, I have downloaded and installed your script and everything works great. Among others I have been searching for a solution for a very long time until I came across this. Your contributions are greatly appreciated, and even if other people don’t have the time to comment and say thanks I am sure they too appreciate your work. Thanks a lot, from New Zealand :)

      • Max

        One last quick question; do you know how to have the custom registration form only for a particular website (in our case for wholesale), and have the standard registration form for the other ‘retail’ store?

  • Anonymous

    How to add Terms and conditions checkbox in customer registration in magento 1.6

    • http://twitter.com/jonathanpath Jonathan Path

      Hey, I also need to know how to make it function with a checkbox. I have too a “Call to a member function getSchool() on a non-object” error message ! Thanks for your help !

  • Anonymous

    did u there sir

  • Raphael

    Manish

  • Raphael

    Hello Manish, i just wanna say thanks for this code and ask you about a problem with multiple fields task.

    I try to make 4 new fields on your code and i get this error:

    /profile_setup/mysql4-install-0.1.0.php” – SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name ‘customer_pfpj’

    My mysql file is look like this:
    ========================================================================
    startSetup();

    $setup = Mage::getModel(‘customer/entity_setup’, ‘core_setup’);

    /* START PFPJ */
    $setup->addAttribute(‘customer’, ‘pfpj’, array(
        ‘type’ => ‘int’,
        ‘input’ => ‘select’,
        ‘label’ => ‘Tipo de Cadastro’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 1,
        ‘user_defined’ => 1,
        ‘default’ => ’0′,
        ‘visible_on_front’ => 1,
        ‘source’ =>     ‘profile/entity_pfpj’,
    ));

    if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();
        $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘pfpj’);
    }

    if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’))
    {
        Mage::getSingleton(‘eav/config’)
        ->getAttribute(‘customer’, ‘pfpj’)
        ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))
        ->save();
    }
    /* END PFPJ */

    /* START Razao Social */
    $setup->addAttribute(‘customer’, ‘razao_social’, array(
        ‘type’ => ‘text’,
        ‘input’ => ‘text’,
        ‘label’ => ‘Razão Social’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 0,
        ‘user_defined’ => 1,
        ‘default’ => ’0′,
        ‘visible_on_front’ => 1,
        ‘source’ =>     ‘profile/entity_razao_social’,
    ));

    if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();
        $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘razao_social’);
    }

    if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’))
    {
        Mage::getSingleton(‘eav/config’)
        ->getAttribute(‘customer’, ‘razao_social’)
        ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))
        ->save();
    }
    /* END Razao Social */

    /* START CNPJ */
    $setup->addAttribute(‘customer’, ‘cnpj’, array(
        ‘type’ => ‘text’,
        ‘input’ => ‘text’,
        ‘label’ => ‘CNPJ’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 0,
        ‘user_defined’ => 1,
        ‘default’ => ’0′,
        ‘visible_on_front’ => 1,
        ‘source’ =>     ‘profile/entity_cnpj’,
    ));

    if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();
        $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘cnpj’);
    }

    if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’))
    {
        Mage::getSingleton(‘eav/config’)
        ->getAttribute(‘customer’, ‘cnpj’)
        ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))
        ->save();
    }
    /* END CNPJ */

    /* START IE */
    $setup->addAttribute(‘customer’, ‘ie’, array(
        ‘type’ => ‘text’,
        ‘input’ => ‘text’,
        ‘label’ => ‘I.E.’,
        ‘global’ => 1,
        ‘visible’ => 1,
        ‘required’ => 0,
        ‘user_defined’ => 1,
        ‘default’ => ’0′,
        ‘visible_on_front’ => 1,
        ‘source’ =>     ‘profile/entity_ie’,
    ));

    if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();
        $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘ie’);
    }

    if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’))
    {
        Mage::getSingleton(‘eav/config’)
        ->getAttribute(‘customer’, ‘ie’)
        ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))
        ->save();
    }
    /* END IE */

    $tablequote = $this->getTable(‘sales/quote’);
    $installer->run(”
    ALTER TABLE  $tablequote ADD  `customer_pfpj` INT NOT NULL;
    ALTER TABLE  $tablequote ADD  `customer_cnpj` INT NOT NULL;
    ALTER TABLE  $tablequote ADD  `customer_razao_social` INT NOT NULL;
    ALTER TABLE  $tablequote ADD  `customer_ie` INT NOT NULL
    “);

    $installer->endSetup();
    ?>
    ========================================================================

    My config.xml is look like this:
    ========================================================================

       
           
                0.1.0
           
       
       
           
               
                    standard
                   
                        Excellence_Profile
                        profile
                   
               
           
           
               
                   
                        profile.xml
                   
               
           
       
       
           
                
                    admin
                    
                        Excellence_Profile
                        profile
                    
                
           
       
       
        
          
               
                 pfpj
            
            
                 razao_social
            
            
                 cnpj
            
            
                 ie
            
          
            
                
                    pfpj
                
               
                    razao_social
               
               
                    cnpj
               
               
                    ie
               
                   
         
        
        
           
               
                     111
                     111
                     111
                     111
               
           
        
       
           
               
                    Excellence_Profile_Model
                    profile_mysql4
               
               
                    Excellence_Profile_Model_Mysql4
                   
                       
                            profile
                       
                   
               
           
           
               
                   
                        Excellence_Profile
                        Mage_Customer_Model_Entity_Setup
                    
                   
                        core_setup
                   
               
               
                   
                        core_write
                   
               
               
                   
                        core_read
                   
               
           
           
               
                    Excellence_Profile_Block
               
           
           
               
                    Excellence_Profile_Helper
               
           
       

    ========================================================================

    This code is running on a clean install of Magento 1.6.1.

    • http://www.facebook.com/lszborges Leonardo De Souza Borges

      Raphael to desenvolvendo um modulo baseado no artigo também… vc já conseguiu adaptar ao caso do brasil? Poderia me dar alguma dica do que fez? Abraços, Léo.

    • C. Rafael

      Cara eu tive este problema de tabela o que acontece é que a acda execução do seu my sql ele tenta criar o campo novamente neste caso o sql deve conter is not existe para que so crie o campo caso ele nao esteja criado bom se esse for todo seu problema pode ser que esteja resolvido mas acho que nosso problema é igual o brasil ser diferente no checkout com campos a mais que todos espero obter sucesso caso isso ocorra eu te ajudo tambem se quiser ok Vlw… e seu codigo acima pode ajudar a nao digitar muitas linha showw

  • Pingback: Adding new attributes | Magento Media

  • http://twitter.com/jonathanpath Jonathan Path

    Hey, I also need to know how to make it function with a checkbox. I have too a “Call to a member function getSchool() on a non-object” error message ! Thanks for your help !

    • Anonymous

                             
                                      
                                                                   

       *I agree to the terms & conditions of eshopchennai.com
       
                     
                 
             

      I have done like this and it works like a charm

      Just put the code in register.phtml and for me i just want for the terms and conditions only

      Check it out guy

  • Eric Cavalcanti

    Hi there.
    Thanks.
    But how could I show on the order on admin?
    Thanks.

  • Eric Cavalcanti

    How can I see the new attribute on the sale?

  • Andrei Boar

    I’ve added an Image file attribute for my customer, but on the front-end it doesn’t show the Delete Image radio button, nor the image as it does in admin. What could it be the problem?

  • amit

     set its class same as in another required field ,it will works.

  • http://twitter.com/sqlinternals D. Miller

    Hi Manish!
    Thank you for this great tutorial!
    I created a custom field using this tutorial, and this attribute cannot be filled by the customer.
    The field name is: ThirdID setThirdid(’0′);
            return parent::_beforeSave();
        }

    But still not works.
    I would like that for each new customer, the attribute ThirdID has one default value equal to zero. Because I need to filter these new customers with SOAP method.
    Can you give me a help to achieve it? Thank you!

  • http://twitter.com/sqlinternals D. Miller

    Hi Manish!

    Thank you for this great tutorial!

    I created a custom field using this tutorial, and this attribute cannot be filled by the customer.

    The field name is: ThirdID setThirdid(’0′);
    return parent::_beforeSave();
    }
    }

    But still not works.

    I would like that for each new customer, the attribute ThirdID has one default value equal to zero. Because I need to filter these new customers with SOAP method.

    Can you give me a help to achieve it? Thank you!

  • sukhdip

    Hello Sir ji need help here… as i have posted earlier also. Please help me to get data into DB. I used your tutorial. Created custom field on magento 1.7. Field is visible. Taking data. But Its not putting data into DB. When I click on account information edit button. Mobile fields is totally blank. Info entered by me at the time of registration is not visible.
    Please guide a suitable way….
    Thanks a lot.

  • http://www.facebook.com/Tahirr.hussain Tahir Hussain

    i m unable to custmize my custmer login and register page… i have changed in appdesignfrontendbasedefaulttemplatecustomerformlogin.phtml and register.phtml files..

    but not even a single change happen after this.. what would be problem with me??

    plz solve this

  • Yaseen

    i am using magento 1.7.0.2, i didnt create any module just add your code (Step 1 If you don’t have a module In this case you do this ) in persistent/customer/form/login.php but its showing me this error

    Fatal error: Call to a member function select() on a non-object in E:xampphtdocscustomerappcodecoreMageCoreModelResourceSetup.php on line 734.. can you please help me

  • disqus_sXw2EjScCd

    Worked superb for me, thanks a million!

    There was one thing that didn’t work for me, I had to execute this query manually in phpMyAdmin to make it work.:

    INSERT INTO `customer_form_attribute` (
    `form_code` ,
    `attribute_id`
    )
    VALUES (
    ‘adminhtml_customer’, ’121′
    ), (
    ‘checkout_register’, ’121′
    ), (
    ‘customer_account_create’, ’121′
    ), (
    ‘customer_account_edit’, ’121′
    );

  • http://www.facebook.com/m.rahman.hamed Mohammed Abdel Rahman

    Thank you. In my case the first line failed $setup = Mage::getModel(‘customer/entity_setup’); because that model customer/entity_setup requires __construct argument $string, which is passed through another method call $setup = Mage::getModel(‘customer/entity_setup’, ‘resourceName’); and i have no idea what’s that resourseName should be. Instead I replaced with $setup = new Mage_Eav_Model_Entity_Setup(‘core_setup’); and then it worked! :) and I will be content if someone would tell me how it worked with you.

  • http://twitter.com/benqbbenqb BEN

    Hi May I know How to edit Customer Address field label ‘company’ to ‘ABN’ in magento in admin panel ?

  • Sean

    Thanks for this – works well in CE 1.702 (thanks to Francois’s little tip below!)

  • http://www.facebook.com/agpjr01 Albert Ponte

    Manish, thanks for the excellent tutorial!! I was wondering how I can access the value in the front-end templates (besides the forms)?

  • Eugene

    Hi,

    thank you for your tutorial. I have added a new field. But it shown only in Backend and not in Frontend (I use magento 1.7.0.2). PLEASE SUPPORT. In Frontend i have an error message like this:

    a:5:{i:0;s:50:”Source model “” not found for attribute “mainarea””;i:1;s:3519:”#0 /home/www/web292/html/eb/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php(387): Mage::exception(‘Mage_Eav’, ‘Source model “”…’)

    #1 /home/www/web292/html/eb/app/design/frontend/ultimo/default/template/mainarea/customer/address/edit.phtml(134): Mage_Eav_Model_Entity_Attribute_Abstract->getSource()

    #2 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Template.php(241): include(‘/home/www/web29…’)

    #3 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template->fetchView(‘frontend/ultimo…’)

    #4 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template->renderView()

    #5 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(863): Mage_Core_Block_Template->_toHtml()

    #6 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(582): Mage_Core_Block_Abstract->toHtml()

    #7 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(522): Mage_Core_Block_Abstract->_getChildHtml(‘customer_addres…’, true)

    #8 /home/www/web292/html/eb/app/code/core/Mage/Page/Block/Html/Wrapper.php(52): Mage_Core_Block_Abstract->getChildHtml(”, true, true)

    #9 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(863): Mage_Page_Block_Html_Wrapper->_toHtml()

    #10 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Text/List.php(43): Mage_Core_Block_Abstract->toHtml()

    #11 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(863): Mage_Core_Block_Text_List->_toHtml()

    #12 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(582): Mage_Core_Block_Abstract->toHtml()

    #13 /home/www/web292/html/eb/app/code/core/Mage/Core/Block/Abstract.php(526): Mage_Core_Block_Abstract->_getChildHtml(‘content’, true)

    #14 /home/www/web292/html/eb/app/design/frontend/ultimo/default/template/page/2columns-left.phtml(49): Mage_Core_Block_Abstract->getChildHtml(‘content’)

  • me

    For those of you who can’t make the new fields in the checkout registration form work, you need to extend Mage/Customer/Model/Resurce/Setup.php, in the function “getDefaultEntities()” add your new fields to the $entities array. It worked for me.

    Hope it helps.

  • Chris Holmes

    Great Tutorial. One question, if you wanted to output this custom value on an email template, what variable would you use? I have tried numerous times and can’t seem to get it to work. Any help would be appreciated! Thanks.

  • Ankita Agrawal

    I am trying to add multiple fields

    I am using this code:-

    startSetup();

    $setup = Mage::getModel(‘customer/entity_setup’, ‘core_setup’);

    $setup->addAttribute(‘customer’, ‘accounttype’, array(

    ‘type’ => ‘int’,

    ‘input’ => ‘select’,

    ‘label’ => ‘Accounttype’,

    ‘global’ => 1,

    ‘visible’ => 1,

    ‘required’ => 0,

    ‘user_defined’ => 1,

    ‘default’ => ’0′,

    ‘visible_on_front’ => 1,

    ‘source’ => ‘profile/entity_accounttype’,

    ));

    $setup->addAttribute(‘customer’, ‘tva’, array(

    ‘type’ => ‘int’,

    ‘input’ => ‘select’,

    ‘label’ => ‘Tva’,

    ‘global’ => 1,

    ‘visible’ => 1,

    ‘required’ => 0,

    ‘user_defined’ => 1,

    ‘default’ => ’0′,

    ‘visible_on_front’ => 2,

    ‘source’ => ‘profile/entity_tva’,

    ));

    $setup->addAttribute(‘customer’, ‘companycountry’, array(

    ‘type’ => ‘varchar’,

    ‘input’ => ‘text’,

    ‘label’ => ‘Companycountry’,

    ‘global’ => 1,

    ‘visible’ => 1,

    ‘required’ => 0,

    ‘user_defined’ => 1,

    ‘default’ => ’0′,

    ‘visible_on_front’ => 4,

    ‘source’ => ‘profile/entity_companycountry’,

    ));

    $setup->addAttribute(‘customer’, ‘companycomment’, array(

    ‘type’ => ‘varchar’,

    ‘input’ => ‘text’,

    ‘label’ => ‘Companycomment’,

    ‘global’ => 1,

    ‘visible’ => 1,

    ‘required’ => 0,

    ‘user_defined’ => 1,

    ‘default’ => ’0′,

    ‘visible_on_front’ => 3,

    ‘source’ => ‘profile/entity_companycomment’,

    ));

    if (version_compare(Mage::getVersion(), ’1.6.0′, ‘getResource()->getEntityType()->getDefaultAttributeSetId();

    $setup->addAttributeToSet(‘customer’, $attrSetId, ‘General’, ‘accounttype’,’tva’,’companycountry’,’companycomment’);

    }

    if (version_compare(Mage::getVersion(), ’1.4.2′, ‘>=’))

    {

    Mage::getSingleton(‘eav/config’)

    ->getAttribute(‘customer’, ‘accounttype’, ‘tva’,’companycountry’,’companycomment’ )

    ->setData(‘used_in_forms’, array(‘adminhtml_customer’,’customer_account_create’,’customer_account_edit’,’checkout_register’))

    ->save();

    }

    $tablequote = $this->getTable(‘sales/quote’);

    $installer->run(”

    ALTER TABLE $tablequote ADD `customer_accounttype` INT NOT NULL,

    ADD `customer_tva` INT NOT NULL,

    ADD `customer_companycountry` varchar(100) NOT NULL,

    ADD `customer_companycomment` varchar(1000) NOT NULL

    “);

    $installer->endSetup();

    but its not working….. Please help me where I am wrong

  • James Pelton

    This worked for me in 1.8, except I needed to change the first line:
    $setup = Mage::getModel(‘customer/entity_setup’);

    to:
    $setup = new Mage_Eav_Model_Entity_Setup(‘core_setup’);

    • Jesse

      I’m also using 1.8 and need it to be a text input instead. Do you have any tips to do so? I tried using the downloadable files and modified them, but essentially broke the site somehow. This is my first magento site, so I’m not very familiar with it.

      Any help would be awesome, thank you.

  • Mark

    Awesome work! Thanks helped me a lot!

  • Jesse

    Can you explain a little better how to use the downloaded files, but instead of creating a select, make it a text input? I tried editing the files myself by changing everything from “school” to my own name and select to text, but it basically broke the site. Any help/tips would be greatly appreciated.

    Thank you

  • Rafael Ortega Bueno

    Thank you for the tutorial because it has been very helpful to me.

    But the customer_school field created in sales_flat_quote table is not set when a request is made becoming impossible to display it in admin order info.

    Have any idea what we can do for this field is set correctly?

  • http://www.perspektive-web.com/ Philipp Schöfer

    Thanks a lot! This helped me very much. Excellent description!

  • Bobismeisbob

    I don’t have a “customer_form_attribute” table, what are the columns?

  • http://www.gabrieloliveira.net/ Gabriel Oliveira

    Thanks, this is very useful for me. Although I not make exactly how you learn (I make a list of admin users to customer, to represent a seller), your post helps a lot.