Magento: How to merge multiple fields in a colum in Magento admin panel grid?
May 3, 2012 | In: Magento, mysql, php, web development
Magento provides lot of inbuild functionalities. Using “protected function _prepareColumns()” function we can create or add new column to the grid.
Like:
protected function _prepareColumns() { $this->addColumn('first_name', array( 'header' => Mage::helper('custommodule')->__('First Name'), 'align' => 'left', 'width' => '50px', 'index' => 'first_name', )); $this->addColumn('last_name', array( 'header' => Mage::helper('custommodule')->__('Last Name'), 'align' => 'left', 'width' => '50px', 'index' => 'last_name', )); } |
But sometimes we have lot of columns for our custom module and we need to merge two columns to single column. So what we have to do?
I explain you how can we do this by programmatically: We can use ‘Renderer’ terms to combine two columns.
Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract |
Step1: Firstly, create a new folder ‘Renderer’ inside the Block/Adminhtml folder of your custom plugin.
Step2: Make a new file called ‘CustomerName.php’ with the below contents:
class Company_Custommodule_Block_Adminhtml_Renderer_CustomerName extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) { if ($row->getData('first_name') != NULL || $row->getData('last_name') != NULL) { $firstName = $row->getData('first_name'); $lastName = $row->getData('last_name'); if ($lastName != NULL) { return $firstName . ' ' . $lastName; } else { return $firstName; } } else { return Mage::helper('dailydeal')->__('NO NAME ASSIGNED'); } } } |
Step3: Then, in the grid, make a new column with calling above rendrerer file:
protected function _prepareColumns() { $this->addColumn('first_name', array( 'header' => Mage::helper('custommodule')->__('First Name'), 'align' => 'left', 'width' => '100px', 'index' => 'first_name', 'renderer' => new Company_Custommodule_Block_Adminhtml_Renderer_CustomerName(), )); } |
I hope it will work for you too…. 🙂