Adding a column to the Orders Grid in Magento sounds like an easy enough request, however when faced with this task myself, it turned out to be less than straight forward. I figured I should blog an up-to-date “How To” on this, since the ones I found on the internet don’t seem to apply to current versions of Magento. So in my particular case, a client had asked that “Company Name” be added to to the orders grid, so I will be using that variable for this example.
First, we’re going to create the following files:
For the first file, Grid.php, instead of extending Mage_Adminhtml_Block_Sales_Order_Grid we’ll want to extend the parent Mage_Adminhtml_Block_Widget_Grid. This is because when the _prepareCollection() function calls the parent::_prepareCollection() function anything we do in our own function will be overridden when the parent is called.
As a result of this, we are going to copy over everything in the Mage_Adminhtml_Block_Sales_Order_Grid file, into Demac_Adminhtml_Block_Sales_Order_Grid. The only variation will be the _prepareCollection() function, which we will copy from Mage_Adminhtml_Block_Widget_Grid.
The first change we will make is in the _prepareCollection() function. We need to do a join before if($this->getCollection) so we are grabbing the attribute we need. To do this, add:
$collection = Mage::getResourceModel($this->_getCollectionClass()); $collection->getSelect()->join(‘sales_flat_order_address’, ‘main_table.entity_id=sales_flat_order_address.parent_id AND sales_flat_order_address.address_type=\’billing\”, ‘company’,NULL); $collection->getSelect()->distinct(); $this->setCollection($collection); just before the if($this->getCollection).
For some reason, the way Magento builds a join using the join() function, you will end up with two copies of each result which is why we do the $collection->getSelect()->distinct(); after the join. Also, notice the AND sales_flat_order_address.address_type=’billing’. This is so that if the order has a different shipping address with a different company name, it will not be grabbed.
Now we need to make an addition to the _prepareColumns() function. Simply add: $this->addColumn(‘company’, array(‘header’ => Mage::helper(‘sales’)->__(‘Company’), ‘index’ => ‘company’, )); in the function after whichever column you would like this one to appear.
The rest should be fairly straight forward for those who have created a module in Magento before. app/code/local/Demac/Adminhtml/etc/config.xml should contain:
and app/etc/modules/Demac_Adminhtml.xml should contain:
Once this is done, we just need to clear the cache and we should be good to go!