Magento – Change Order Grid Overwrite Problem

adminhtmlgridmagento-1moduleorder-grid

I try to change Order Grid, but I don't know where I have a problem …
There is my files:

app/code/local/My/Module/etc/config.xml

<?xml version="1.0"?>
<config>        
    <global>
        <blocks>
            <adminhtml>
                <rewrite>
                    <sales_order_grid>My_Module_Block_Adminhtml_Order_Grid</sales_order_grid>
                </rewrite>
            </adminhtml>
        </blocks>
    </global>
</config>

Inside app/code/local/My/Module/Block/Adminhtml/Order/Grid.php I've just copy the methods from Mage_Adminhtml_Block_Sales_Order_Grid change class name to My_Module_Block_Adminhtml_Order_Grid and comment out this:

    $this->addColumn('grand_total', array(
        'header' => Mage::helper('sales')->__('G.T. (Purchased)'),
        'index' => 'grand_total',
        'type'  => 'currency',
        'currency' => 'order_currency_code',
    ));

I expected that G.T. (Purchased) disappear but is not.
So i tried another easier way. I've just copy app\code\core\Mage\Adminhtml\Block\Sales\Order\Grid.php to app\code\local\Mage\Adminhtml\Block\Sales\Order\Grid.php and repeat action but still nothing. I'm totally Magento Newbie so please to some help.

Best Answer

Yes that's a known issue when overriding grid blocks.

Basically the problem is that your My_Module_Block_Adminhtml_Order_Grid::_prepareColumns() method returns return parent::_prepareColumns(); which means it returns Mage_Adminhtml_Block_Sales_Order_Grid::prepareColumns()

Thus the changes you are doing in your custom class are overwritten by the original class.

To fix the issue, replace:

return parent::_prepareColumns();

With:

return Mage_Adminhtml_Block_Widget_Grid::_prepareColumns();

In your custom block class. It will fix the issue.

Using observers instead of block rewrite

On a side note, instead of rewrite the entire block class, which can cause issues when upgrading Magento and/or conflicts with other extensions, I can suggest you use event observers to remove your unwanted column:

Under your config.xml, add:

<adminhtml>
    <events>
        <!-- Called before HTML render -->
        <adminhtml_block_html_before>
            <observers>
                <custom_before_block>
                    <type>model</type>
                    <class>modulename/observer</class>
                    <method>blockBeforeHtml</method>
                </custom_before_block>
            </observers>
        </adminhtml_block_html_before>
    </events>
</adminhtml>

Then create your Model/Observer.php:

<?php 

class Vendor_Modulename_Model_Observer
{
    public function blockBeforeHtml(Varien_Event_Observer $observer)
    {
        $block = $observer->getBlock();
        if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Grid)
        {
            $block->removeColumn('grand_total');
        }
    }
}
Related Topic