home

Add custom eav customer attribute in Magento.

October 23, 2017

Recently i needed to create a custom field that would save a customer’s industry on signup I wanted to achieve this with as little custom code as possible and this is how.

In my module i have created a setup script with the following:

$installer = $this;

$installer->startSetup();

try {  
  $setup = new Mage_Eav_Model_Entity_Setup('core_setup');

  $setup->addAttribute(
    'customer',
    'industry',
    array(
      'group'                => 'General',
      'type'                 => 'int',
      'label'                => 'Industry',
      'input'                => 'select',
      'source'               => 'mymodule_custom/config_source_items',
      'global'               => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
      'required'             => 1,
      'default'              => null,
      'visible_on_front'     => 1,
      'used_for_price_rules' => 0,
      'adminhtml_only'       => 0,
    )
  );

  Mage::getSingleton('eav/config')
    ->getAttribute('customer', 'industry')
    ->setData('used_in_forms', array('adminhtml_customer', 'customer_account_create'))
    ->save();

}
catch (Exception $e) {  
  Mage::logException($e);
}

$installer->endSetup();

There are some points to know with the setup script:

  • type: As we are using the customer eav attribute there are only limited types:

    • int
    • text
    • varchar
  • input: This is the frontend type e.g selectbox, radio etc.
  • source: I’m using my own source model to get the values to save. I created a source model: app/code/local/MyModule/Custom/Model/Config/Source/Items.php

Inside this Source model I’m returning a collection of items stored in the database

class MyModule_Custom_Model_Config_Source_Items extends Mage_Eav_Model_Entity_Attribute_Source_Abstract {

  /**
    * Get options in "key-value" format
    *
    * @return array
    */
  public function getAllOptions()
  {
    return Mage::getModel('mymodule_custom/item')->getCollection()->toOptionArray();
  }
}

Another thing to note in the setup script is the following:

Mage::getSingleton('eav/config')
  ->getAttribute('customer', 'industry')
  ->setData('used_in_forms', array('adminhtml_customer', 'customer_account_create'))
  ->save();

Settings the data for usedinforms allows your custom customer attribute to be used on forms.

If you look at mage/core/customer/controllers/AccountController.php method _getCustomerForm() this method calls $customerForm->setFormCode('customer_account_create'); when rendering forms it checks all the eav customer attributes against customer_form_attribute to see if it can be rendered on that form.

MYSQL view of customer attribute table

And that’s it, no custom code required! :)