Monday, February 6, 2012

how to add custom field in customer registration form in front end and admin end magento 1.6.X

let you want to add occupation for customer registration
1. Add the following code in the form tag in register.phtml and edit.phtml
app/design/frontend/default/yourstore/template/customer/form/register.html 

////////////////
 <div class="input-box">

                    <label for="occupation"><?php echo $this->__('Occupation') ?></label><br/>

                    <input type="text" name="occupation" id="occupation" value="<?php echo $this->htmlEscape($this->getFormData()->getOccupation()) ?>" title="<?php echo $this->__('Occupation') ?>" class="input-text" />

                </div> 

/////////////////

2. replace the following block of code in
app/code/core/Mage/Customer/Model/Resource/Setup.php

//////////
 'group_id'           => array(
                        'type'               => 'static',
                        'label'              => 'Group',
                        'input'              => 'select',
                        'source'             => 'customer/customer_attribute_source_group',
                        'sort_order'         => 25,
                        'position'           => 25,
                        'adminhtml_only'     => 1,
                        'admin_checkout'     => 1,
                    ),     
///////////

with this
////////////

 'group_id'           => array(
                        'type'               => 'static',
                        'label'              => 'Group',
                        'input'              => 'select',
                        'source'             => 'customer/customer_attribute_source_group',
                        'sort_order'         => 25,
                        'position'           => 25,
                        'adminhtml_only'     => 1,
                        'admin_checkout'     => 1,
                    ),                   
                    'occupation'          => array(
                        'type'               => 'varchar',
                        'label'              => 'Occupation',
                        'input'              => 'text',
                        'sort_order'         => 7,
                        'validate_rules'     => 'a:2:{s:15:"max_text_length";i:255;s:15:"min_text_length";i:1;}',
                        'position'           => 120,
                    ),
///////////

3. find the following line of code around line 280  in
app/code/core/Mage/Customer/controllers/AccountController.php

///////
 $customerData = $customerForm->extractData($this->getRequest());
//////

and replace with
////////////
 $customerData = $customerForm->extractData($this->getRequest());
           //new code added to save occupation in database start here
            if($this->getRequest()->getParam('occupation'))
             {
                 $customer->setOccupation($this->getRequest()->getParam('occupation'));
                
             } 
              //new code added to save occupation in database end here
           

///////////

4. add the following code in
app/code/core/Mage/Customer/etc/config.xml
your
under the customer_account

////////
<occupation>
                 <create>1</create>
                 <update>1</update>
              </occupation>
//////

5. put this script in your register.phtml 's header file and remove it after one run
 <?php
  
     $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
  
    $AttrCode = 'occupation';
  
      $settings = array (
  
          'position' => 1,
  
          'is_required'=> 0
  
      );
  
      $setup->addAttribute('1', $AttrCode, $settings);
  
      ?>



To show this field in admin end in customer tab field


1. find and replace this function of code in
app/code/core/Mage/AdminHtml/Block/Customers/Grid.php

/////////////////
 protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('customer/customer_collection')
            ->addNameToSelect()
            ->addAttributeToSelect('email')
            ->addAttributeToSelect('created_at')
            ->addAttributeToSelect('group_id')
            ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
             ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
            ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
            ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
            ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }
/////////////////// 

and replace with

//////////////////
 protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('customer/customer_collection')
            ->addNameToSelect()
            ->addAttributeToSelect('email')
            ->addAttributeToSelect('occupation')
            ->addAttributeToSelect('created_at')
            ->addAttributeToSelect('group_id')
            ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
             ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
            ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
            ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
            ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }
/////////////////// 



2. find and replace this function of code in
app/code/core/Mage/AdminHtml/Block/Customers/Grid.php


///////////
protected function _prepareColumns()
    {
        $this->addColumn('entity_id', array(
            'header'    => Mage::helper('customer')->__('ID'),
            'width'     => '50px',
            'index'     => 'entity_id',
            'type'  => 'number',
        ));
        $this->addColumn('firstname', array(
            'header'    => Mage::helper('customer')->__('First Name'),
            'index'     => 'firstname'
        ));
        $this->addColumn('lastname', array(
            'header'    => Mage::helper('customer')->__('Last Name'),
            'index'     => 'lastname'
        ));
       /* $this->addColumn('name', array(
            'header'    => Mage::helper('customer')->__('Name'),
            'index'     => 'name'
        ));*/
        $this->addColumn('email', array(
            'header'    => Mage::helper('customer')->__('Email'),
            'width'     => '150',
            'index'     => 'email'
        ));
        $this->addColumn('occupation', array(
            'header'    => Mage::helper('customer')->__('Occupation'),
            'width'     => '150',
            'index'     => 'occupation'
        ));

        $groups = Mage::getResourceModel('customer/group_collection')
            ->addFieldToFilter('customer_group_id', array('gt'=> 0))
            ->load()
            ->toOptionHash();

        $this->addColumn('group', array(
            'header'    =>  Mage::helper('customer')->__('Group'),
            'width'     =>  '100',
            'index'     =>  'group_id',
            'type'      =>  'options',
            'options'   =>  $groups,
        ));

        $this->addColumn('Telephone', array(
            'header'    => Mage::helper('customer')->__('Telephone'),
            'width'     => '100',
            'index'     => 'billing_telephone'
        ));

        $this->addColumn('billing_postcode', array(
            'header'    => Mage::helper('customer')->__('ZIP'),
            'width'     => '90',
            'index'     => 'billing_postcode',
        ));

        $this->addColumn('billing_country_id', array(
            'header'    => Mage::helper('customer')->__('Country'),
            'width'     => '100',
            'type'      => 'country',
            'index'     => 'billing_country_id',
        ));

        $this->addColumn('billing_region', array(
            'header'    => Mage::helper('customer')->__('State/Province'),
            'width'     => '100',
            'index'     => 'billing_region',
        ));

        $this->addColumn('customer_since', array(
            'header'    => Mage::helper('customer')->__('Customer Since'),
            'type'      => 'datetime',
            'align'     => 'center',
            'index'     => 'created_at',
            'gmtoffset' => true
        ));

        if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('website_id', array(
                'header'    => Mage::helper('customer')->__('Website'),
                'align'     => 'center',
                'width'     => '80px',
                'type'      => 'options',
                'options'   => Mage::getSingleton('adminhtml/system_store')->getWebsiteOptionHash(true),
                'index'     => 'website_id',
            ));
        }

        $this->addColumn('action',
            array(
                'header'    =>  Mage::helper('customer')->__('Action'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getId',
                'actions'   => array(
                    array(
                        'caption'   => Mage::helper('customer')->__('Edit'),
                        'url'       => array('base'=> '*/*/edit'),
                        'field'     => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
                'is_system' => true,
        ));

        $this->addExportType('*/*/exportCsv', Mage::helper('customer')->__('CSV'));
        $this->addExportType('*/*/exportXml', Mage::helper('customer')->__('Excel XML'));
        return parent::_prepareColumns();
    }
///////////////

3...find the following line of code in
app\code\core\Mage\Adminhtml\Block\Customer\Edit\Tab\Account.php

/////
$suffixElement = $form->getElement('suffix');
        if ($suffixElement) {
            $suffixOptions = $this->helper('customer')->getNameSuffixOptions($customerStoreId);
            if (!empty($suffixOptions)) {
                $fieldset->removeField($suffixElement->getId());
                $suffixField = $fieldset->addField($suffixElement->getId(),
                    'select',
                    $suffixElement->getData(),
                    $form->getElement('lastname')->getId()
                );
                $suffixField->setValues($suffixOptions);
                if ($customer->getId()) {
                    $suffixField->addElementValues($customer->getSuffix());
                }
            }
        }
      
//////

and replace with
//////////////////////////////
$suffixElement = $form->getElement('suffix');
        if ($suffixElement) {
            $suffixOptions = $this->helper('customer')->getNameSuffixOptions($customerStoreId);
            if (!empty($suffixOptions)) {
                $fieldset->removeField($suffixElement->getId());
                $suffixField = $fieldset->addField($suffixElement->getId(),
                    'select',
                    $suffixElement->getData(),
                    $form->getElement('lastname')->getId()
                );
                $suffixField->setValues($suffixOptions);
                if ($customer->getId()) {
                    $suffixField->addElementValues($customer->getSuffix());
                }
            }
        }
        ///new code start here
         $fieldset->addField('occupation', 'text', array(
            'name'      => 'occupation',
             'label'=>'Occupation'
            
            ));
        
         ///new field end here



/////////////////////////////

4.find the follwing line of code around line no. 280 in file
app\code\core\Mage\Adminhtml\controllers\CustomerController.php

///////////////

if (isset($data['subscription'])) {
                $customer->setIsSubscribed(true);
            } else {
                $customer->setIsSubscribed(false);
            }
 ////////////////

and replace with
///////////////

if (isset($data['subscription'])) {
                $customer->setIsSubscribed(true);
            } else {
                $customer->setIsSubscribed(false);
            }
           //new code added to save occupation in database start here
          
            if(isset($data['account']['occupation']))
             {
              
                 $customer->setData('occupation',$data['account']['occupation']);
                
             } 
             //new code added to save occupation in database end here
///////////////



Enjoy !!!!!!!!

41 comments:

  1. Really nice work... thanks buddy you save my time

    ReplyDelete
  2. Really very nice.. :)Helped a lot and saved time ..:)

    Good work keep posting..

    ReplyDelete
  3. Gone through this and nothing worked, I'm on version 1.7 can anyone please help?

    ReplyDelete
    Replies
    1. Sorry for late response. This code is also working with magento 1.7. Please check every step that i mentioned in above solution.

      Delete
  4. dear how can i add more than one field ? please help

    ReplyDelete
    Replies
    1. Dear Hassan,
      you can add more than one field with the above given solution.Plz review the code and you will find the way.If you unable to do such ,let me inform.

      Thanks
      Vinod

      Delete
  5. Vinod, Great tutorial! Works like a charm in Magento 1.7
    Can you please help me in creating a dropdown menu on the checkout page?
    My organization wants 'How did you hear about us?' field as a dropdown and I didn't find any good solution anywhere.

    Regards,
    Deepesh

    ReplyDelete
  6. Hi,
    Thanks for your extensive tutorial. It has helped me on the way, but I couldn't get the last part done; in app\code\core\Mage\Adminhtml\controllers\CustomerController.php there's no

    if (isset($data['subscription'])) {
    $customer->setIsSubscribed(true);
    } else {
    $customer->setIsSubscribed(false);
    }

    anymore, as these lines of code have been separated into two different functions since Magento 1.7 (or perhaps an earlier version). So, I don't know where to add the code given by you and adding them somewhere else in the file doesn't do the trick for me.

    Could you please help me out with this perhaps? I'd be very grateful :)

    ReplyDelete
    Replies
    1. Hi,

      You can add this line of code
      //new code added to save occupation in database start here

      if(isset($data['account']['occupation']))
      {
      $customer->setData('occupation',$data['account']['occupation']);
      }
      //new code added to save occupation in database end here

      after this
      //////////////

      if (Mage::getSingleton('admin/session')->isAllowed('customer/newsletter')) {
      $customer->setIsSubscribed(isset($data['subscription']));
      }
      //////////
      in the saveAction() in mentioned file.
      If any query plz let me know.


      Thanks

      Delete
  7. I have added 2 fields phone and fax in registration form in front end and both are being saved in database and displaying in the edit Account Information form after login. But when I try to edit the value of any of newly created(Phone,Fax) fields, values are not being updated. Edit account information form is working fine for other fields. It is not working only for these 2 newly created fields.

    Please suggest about the same.

    ReplyDelete
    Replies
    1. Hi Amit,

      can you check the above process again in your code file? Make sure you did allowed to update you fields in app/code/core/Mage/Customer/etc/config.xml .

      in config.xml for your both filed. Also check the save action carefully.
      In My end this is working for one and more fields.

      Thanks

      Delete
    2. Hi Kumar,
      Edit is not working for me also.

      I have used $this->getCustomer()->getOccupation()) instead of $this->getFormData()->getOccupation())

      Bcz when I use $this->getFormData()->getOccupation()) in edit file then edit URL is not showing all fields that's why I have changed it a bit.

      So now it's showing all fields when I am in edit URL but is not changed data in admin.

      Also I have added below code in config file


      1
      1


      register file path: app/design/frontend/default/CMS/template/persistent/customer/form
      edit file path: app/design/frontend/default/CMS/template/customer/form

      Please let me know if any solution.

      Delete
  8. I am using Magento 1.7.0.2

    ReplyDelete
  9. Yor have such a nice tutorial u save mah lot of time .. thx

    ReplyDelete
  10. Thanks a lot bro... you are genius... :)

    ReplyDelete
  11. hey would you please post how to add dropdownlist box in the registration form ?! i can see the field at the front end but i cant see it on the backend!!

    ReplyDelete
    Replies
    1. Hi,
      you can manage the select field like 'Customer Group' in backend. Please have see your Admin Grid.php and Admin controller care fully.

      Delete
    2. hello vinod , i'm getting same problem it does not show in backend

      Delete
  12. Hello Vinod Thanks !!! it was not showing due to not setting the input type as select!!

    thnx for reply!!

    ReplyDelete
  13. Great Tutorial.....Vinod. Can you help how to add personalization on product page...
    My email id is php.dev1987@gmail.com

    ReplyDelete
    Replies
    1. Hi Dev,

      Thanks for your comment. You can show the product's custom information with the help of attribute.
      Or anything else you want plz tell me in brief what type information you want to show on my email kumarvinod1986@gmail.com

      Delete
  14. hi,its very easy to understand,i use magento 1.7 but i followed your step by step process to create mobile number on my registration page.but its only show on the front end.when click to edit link after register not show any mobile number value of registered user.please help me...ca i create a filed as mobilenumber on the table? i will waiting for your responds..please ...

    ReplyDelete
  15. Vinod,
    Really great and easy.

    My Query:

    I am using version 1.7 and didnt find CustomerController.php file on path: app\code\core\Mage\Adminhtml\controllers\ though I success to add 1 field and it display in admin too but didnt display in on front-end in 'Account information'. Is this because i could not add code in CustomerController.php ?

    Thanks,
    Jai

    ReplyDelete
  16. Bad technique to customize Magento. You should follow standards of customizing Magento using event observers and class rewrites.

    ReplyDelete
  17. Yes upto some extent it is bad technique to customize Magento as this will direct tampering/customization with the Magento core modules. Instead of doing this it should be done by overriding technique

    ReplyDelete
  18. hello vinod , occupation field does not show in customer admin section

    ReplyDelete
  19. Hi , the code is not working , I have tried to add new field in address. Please guide me.

    Thanks

    Sheetal

    ReplyDelete
  20. It is working gr8 from admin but from Front end value never stores in database.
    Please coould you tell me that how can I add field in address?

    Thanks,
    Sheetal

    ReplyDelete
  21. Hi Vinod
    ts very easy to understand,i use magento 1.7 but i followed your step by step process to create mobile number on my registration page.but its only show on the front end.
    when click to edit link after register not show any mobile number value of registered user.
    And when click to Managment customer not show any mobile field in customer grid list
    please help me...can i create a filed as mobilenumber on the table? i will waiting for your responds..please

    ReplyDelete
  22. Hi,

    I have followed the same and but new occupation field is not showing in registration form? But I can see its there in admin section.What can be the reason?

    Thanks

    ReplyDelete
  23. Thanks for the tutorial, Vinod!
    But if I want to multiple select for additional fields (e.g. to add people to multiple customer groups), what should I do? Would be easier for me to install an extension? BTW, could you recommend any? I found this one http://amasty.com/address-attributes.html, what'd you say?

    ReplyDelete
  24. Thanks for this nice tutorial.

    ReplyDelete
  25. Thanks a lot bro... you are genius... :)

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. i done all the step what define but i am new with magento so how i find out in which table field data save

    ReplyDelete
  28. i added mobile field its showing a column but not showing a column value ..i m stuck..pls any one help me

    ReplyDelete
  29. Good work, In order to add multiple types of custom fields to Magento registration form, I would recommend to try FME additional custom registration form fields extension. You can file upload field,, image, text area, drop down, checkboxes, Yes/No and many more.
    More Info: https://www.fmeextensions.com/magento-additional-registration-attributes-fields.html

    ReplyDelete