Displaying Custom Customer Attribute in Magento Grid
As an experienced developer for Laravel Company, I often encounter queries about extending Magento’s default functionality to meet specific business needs. One such common question is how to display a custom customer attribute in the admin grid.
Creating and Registering a Custom Customer Attribute
To begin, you’ll need to create your new customer attribute using the addAttribute method within the installer:
$installer->addAttribute('customer', 'forum_username', array(
'type' => 'varchar',
'input' => 'text',
'label' => 'Forum username',
'global' => 1,
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'default' => '',
'visible_on_front' => 1
));
Adding the Custom Column to the Grid
Next, extend Mage_Adminhtml_Block_Customer_Grid and add your new column using the _prepareColumns method:
protected function _prepareColumns()
{
$this->addColumnAfter('forum_username', array(
'header' => Mage::helper('customization')->__('Forum user name'),
'index' => 'forum_username',
'type' => 'text'
), 'email');
return parent::_prepareColumns();
}
Fetching the Custom Attribute Value
The challenge lies in fetching the actual value of your custom attribute (forum_username) from the grid. You can use the joinAttribute method for this, but you need to understand its syntax and parameters.
Here’s a correct way to fetch the postcode using this method:
->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
The key is understanding that forum_username belongs to the customer entity, not an address or another related entity. This leads us to the correct syntax:
->joinAttribute('forum_username', 'customer/forum_username')
A Step-by-Step Guide
Let me walk you through the entire process:
- Define your custom attribute as shown above.
- Extend
Mage_Adminhtml_Block_Customer_Gridand add your new column using_prepareColumns. - In your grid collection, use
getSelect()to modify the query.
$collection = $this->getCollection()->getSelect();
- Add the necessary join condition:
$collection->joinAttribute('forum_username', 'customer/forum_username')
->where('main_table.entity_id IN (?)', array($entityId));
Remember to replace $entityId with your specific customer ID.
Conclusion
Displaying a custom customer attribute in Magento’s admin grid requires careful configuration of the attribute and strategic use of the joinAttribute method. By following this guide, you should be able to successfully add new columns to the grid and fetch the values of your custom attributes efficiently.
For more advanced techniques and best practices for extending Magento, I recommend checking out our resources on Magento development at Laravel Company.