I need to show Company Name in sales order grid. These are the files I created:
config.xml
<adminhtml>
<events>
<adminhtml_block_html_before>
<observers>
<addCompanyNameToSalesOrderGrid>
<class>Cpu_CustomGrid_Model_Observer</class>
<method>addCompanyNameToSalesOrderGrid</method>
</addCompanyNameToSalesOrderGrid>
</observers>
</adminhtml_block_html_before>
</events>
</adminhtml>
Observer.php
<?php
class Cpu_CustomGrid_Model_Observer extends Varien_Event_Observer
{
public function addCompanyNameToSalesOrderGrid(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$this->_grid = $event->getBlock();
if ($this->_grid instanceof Mage_Adminhtml_Block_Sales_Order_Grid) {
$this->_collection = $this->_grid->getCollection();
$this->_collection->joinAttribute('company', 'customer_address/company', 'default_billing', null, 'left');
$this->_collection->addAttributeToSelect('company');
$columnData = array(
'header' => 'Company Name',
'index' => 'company',
'type' => 'text',
);
$this->_grid->addColumnAfter('company', $columnData, 'name');
$this->_grid->sortColumnsByOrder();
// rebuild the filters
$filter = $this->_grid->getParam($this->_grid->getVarNameFilter(), null);
if (is_null($filter)) {
$this->_collection->load();
}
$this->_collection->clear();
if (is_string($filter)) {
$data = $this->_grid->helper('adminhtml')->prepareFilterString($filter);
$this->_setFilterValues($data);
} else {
if ($filter && is_array($filter)) {
$this->_setFilterValues($filter);
}
}
// force a reload of the collection
$this->_collection->load();
}
}
protected function _setFilterValues($data)
{
foreach ($this->_grid->getColumns() as $columnId => $column) {
if (isset($data[$columnId]) && (!empty($data[$columnId]) || strlen($data[$columnId]) > 0)
&& $column->getFilter()
) {
$column->getFilter()->setValue($data[$columnId]);
$this->_addColumnFilterToCollection($column);
}
}
return $this;
}
protected function _addColumnFilterToCollection($column)
{
if ($this->_collection) {
$field = ($column->getFilterIndex()) ? $column->getFilterIndex() : $column->getIndex();
if ($column->getFilterConditionCallback()) {
call_user_func($column->getFilterConditionCallback(), $this->getCollection(), $column);
} else {
$cond = $column->getFilter()->getCondition();
if ($field && isset($cond)) {
$this->_collection->addFieldToFilter($field, $cond);
}
}
}
return $this;
}
}
Unfortunately I cannot get it to work. What could be the problem?