Magento – Best Practice: How to add a column to a backend grid

collection;event-observergridlayoutoverrides

Usually we need to add to the Order Grid some column, so let take this as example.

There are 3 ways to do that:

  1. Rewrite the grid block in our custom module
  2. Use an observer on the event core_block_abstract_prepare_layout_before
  3. Use a Layout update

(let don't consider the alteration of the collection to make things more easy)

  • First method is the most powerful but It leads to conflict in the scenarios.
  • Second method is in IMHO resource consuming as we are adding an extra code step for every block we are going to render
  • Third step is a layout update so should be the most advisable … but are we sure it will work always ?

Other consideration are welcome

References:
Method 1:
http://inchoo.net/ecommerce/magento/programming-magento/adding-customer-group-column-to-sales-grid-in-magento/
Method 2:
http://www.atwix.com/magento/add-column-to-customers-grid-alternative-way/
Method 3:
http://www.atwix.com/magento/column-to-orders-grid/

Best Answer

Best practice to add a column to the backend grid is of course implementation of event-observer method. But question arises which event is used for the purpose? And one of the Answer is core_block_abstract_to_html_before

Suppose say you have implemented observer model for above event with method coreBlockAbstractToHtmlBefore.

CODE:

public function coreBlockAbstractToHtmlBefore(Varien_Event_Observer $observer)
{

    /** @var $block Mage_Core_Block_Abstract */
    $block = $observer->getEvent()->getBlock();
    if ($block->getId() == 'customerGrid')
    {
        // Add the attribute as a column to the grid
        $block->addColumnAfter(
            'custom_grid_element',
            array(
                'header' => $helper->__('Custom Grid Element'),
                'align' => 'center',
                'width' => '80px',
                'type' => 'text',
                'options' => array(
                ),
                'default' => '',
                'index' => 'custom_grid_element',
                'renderer'  => ''
            ),
            'customer_since'
        );

        // Set the new columns order.. otherwise our column would be the last one
        $block->sortColumnsByOrder();
    }
}

Above is just an example for adding custom grid element to the Customer grid. You can deploy the very same technique for Sales grid as well.

Related Topic