Creating Customer Attributes

Sometimes you need to save and integrate additional information about customers using the built in Customer Attribute model. By programatically adding customer attributes not only does it make deployment and adding to your website a snap. If wrapped in an extension using a install script, all developers will be on the same page with an auto upgrade.
The code snippet below adds a customer attribute of type integer. The attribute is configured with a global scope & is not required to be saved with each Customer.

The second part of the code adds the attribute to the account information tab in the users login area and also allows you to edit the attribute via the the backoffice admin area.

For a complete list of how the attribute can be used in forms run the query below which will out put a list list:

  • ‘adminhtml_checkout’
  • ‘adminhtml_customer’
  • ‘adminhtml_customer_address’
  • ‘checkout_register’
  • ‘customer_account_create’
  • ‘customer_account_edit’
  • ‘customer_address_edit’
  • ‘customer_register_address’

To install the attribute, add the code or similar under your sql directory for your upgrade script (e.g. mysql4-install-1.0.0.php)

SELECT DISTINCT form_code FROM `customer_form_attribute` WHERE 1
$setupModel = Mage::getModel('eav/entity_setup', 'core_setup');
$eavConfig = Mage::getSingleton('eav/config');
$attributeCode = 'new_attribute'; // Magento seems to prefer lower case naming convention with underscores
$attributeLabel = 'New Attribute';
$data = array(
'type' => 'varchar',
'input' => 'text',
'label' => $attributeLabel,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'is_required' => false,
'is_comparable' => false,
'is_searchable' => false,
'is_unique' => '1',
'is_configurable' => '1',
'user_defined' => '1',
'grid' => '1',
'adminhtml_only' => '1',
'visible' => '1'
);
$setupModel->addAttribute('customer', $attributeCode, $data);
/* Make it visible in the backend for administrators and for the frontend user */
$usedInForms = array (
'adminhtml_customer',
'customer_account_create',
'customer_account_edit',
);
$attribute = $eavConfig->getAttribute('customer', $attributeCode);
$attribute->setData('used_in_forms', $usedInForms)
//->setData("is_used_for_customer_segment", true)
->setData('is_system', 0)
->setData('is_user_defined', 1)
->setData('is_visible', 1)
->setData('is_required', 0);
//->setData("sort_order", 100);
$attribute->save();