Wednesday, May 1, 2013

Add new custom field to "Customer Account Page & Admin Area" - Magento 1.6.X & 1.7.X

Here we explained about to add custom fields in user registration page and admin in our magento how to add new custom field in Customer Account & also in Admin Area for Magento 1.6.X. This is very easy, we just need to do some custom code.



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
///////////////




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

QUESTION: 

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). 

ANSWER:

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']));
}
//////////




==================+++++++++++++++++++++++++++++++++++++++++++++

Method 2


The client wanted to have some extra fields in customer's registration form. At first I added one custom field to customer and then added textfield to registration form. This is how I added a custom textfield to customer entity.
I created a custom module for Magento. I created folder for my module to/app/code/local/company/modulename/.  I also created config file:/app/code/local/company/modulename/etc/config.xml.

<?xml version="1.0"?>
   <config>
      <modules>
         <Companyname_Modulename>
            <version>0.1.0</version>
         </Companyname_Modulename>
      </modules>
      <global>
         <resources>
            <Companyname_Modulename_setup>
               <setup>
                  <module><Companyname_Modulename></module>
                     <class>Companyname_Modulename_Model_Resource_Mysql4_Setup</class>
               </setup>
            </Companyname_Modulename_setup>
         </resources>
      </global>
   </config>
 
On the config file, I define the module name, version and installer. Installer file must be named as mysql4-install-0.1.0.php. Make sure that the version of the module is same than on the filename of the install file. I placed my install file to/app/code/local/companyname/modulename/sql/Companyname_Modulename_setup/.
 
Here is my install file:
 
<?php
$installer = $this;
$installer->startSetup();
 
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
 
$entityTypeId     = $setup->getEntityTypeId('customer');
$attributeSetId   = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);
 
$setup->addAttribute('customer', 'resale', array(
    'input'         => 'text',
    'type'          => 'varchar',
    'label'         => 'Resale number',
    'visible'       => 1,
    'required'      => 1,
    'user_defined' => 1,
    'global' =>1,
    'visible_on_front'  => 1,
));
 
$setup->addAttributeToGroup(
 $entityTypeId,
 $attributeSetId,
 $attributeGroupId,
 'resale',
 '999'  //sort_order
);
 
$oAttribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'resale');
$oAttribute->setData('used_in_forms', array('adminhtml_customer','customer_account_create','customer_account_edit'));
$oAttribute->save();
$installer->endSetup();

In the installer will setup new field to customer entity by making some database changes. I also addedSetup.php file to /app/code/local/companyname/modulename/Model/Resource/Mysql4/. This is the contents of the file:

<?php
class Companyname_Modulename_Model_Resource_Mysql4_Setup extends Mage_Core_Model_Resource_Setup {
}
?>
 
Now after clearing Magento's cache and I saw new field in a customer when creating new customer or editing as admin. The field does not yet show on the registration page. To make it show, I had to edit template file /app/design/frontend/default/mytemplate/template/persistent/customer/form/register.phtml. I added these lines:
 
<div class="field resalenum">
   <label for="resale" class="required"><em>*</em><?php echo $this->__('Resale number') ?></label>
   <div class="input-box">
     <input type="text" name="resale" id="resale" value="<?php echo $this->htmlEscape($this->getFormData()->getResale()) ?>" title="<?php echo $this->__('resale') ?>" class="input-text required-entry" />
</div>
 
I also added same lines to customer's account information editing page. I edited this template file /app/design/frontend/default/mytemplate/template/persistent/customer/form/edit.phtml.

By PHP with 5 comments

5 comments:

Hello,
THis code is not working in 1.8.0.1

I didn't see that code in file

app\code\core\Mage\Adminhtml\controllers\CustomerController.php

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

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

occupation fiels has been show in every customer infomation page but they can not store in database why, in whict table in store occupation field in databse please give me any solution

occupation fiels has been show in every customer infomation page but they can not store attribute value in database why, in whict table in store occupation field in databse please give me any solution

Hi this works nice...i need to add radio button also how todo that..kindly help me

Post a Comment

    • Popular
    • Categories
    • Archives