Magento – Magento grid column filter by text instead of id

filtergridmagento-1.9renderer

I created a column for my grid using renderer to change id to name like this:

$this->addColumn(
            'city_destination',
            array(
                'header' => Mage::helper('test_shippingcost')->__('City Destination'),
                'index'  => 'city_destination',
                'type'=> 'text',
                'renderer'  => 'Test_ShippingCost_Block_Adminhtml_Renderer_City'
            )
        );

But when i want try to filter the value using text, it won't budge unless i'm using id

renderer:

class Test_ShippingCost_Block_Adminhtml_Renderer_City extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
  public function render(Varien_Object $row)
  {
    $id =  $row->getData($this->getColumn()->getIndex());
    $collection = Mage::getModel('test_shippingcost/city')->load($id);
    $value = $collection->getName();
    return $value;
  }
}

Best Answer

This may help

https://www.atwix.com/magento/grid-filter-for-columns/

Add a filter_condition_callback

$this->addColumn(
                'city_destination',
                array(
                    'header' => Mage::helper('test_shippingcost')->__('City Destination'),
                    'index'  => 'city_destination',
                    'type'=> 'text',
                    'renderer'  => 'Test_ShippingCost_Block_Adminhtml_Renderer_City'
                    'filter_condition_callback' => array($this, '_filterCityDestinationCallback')
                )
            );

Then add

   protected function _filterCityDestinationCallback($collection, $column) {
        $value= $column->getFilter()->getValue();
        if (!$value) {
              return $this;
        }
        $this->getCollection()->getSelect()->where("main_table.name like ?","%$value%");                   
        return $this;
   }
Related Topic