Magento - GRID FILTER FOR COLUMNS WITH COMPLEX VALUES
In previous articles we told you how to operate with columns in adminhtml grids. Usually the process is quite fast, for example, if you want to add simple column from the database. But sometimes you need to add column with complex value, processed by renderer. You say: “it’s not a big deal to use renderers…” Right, until you face with sort and filter.. By default Magento applies grid filter directly to the corresponding column. But renderer might contain data from separate columns. At this point we need to choose right way to make filter and sort work correctly. For example, we are going to add a new column “Address” to the orders grid which consists of the values from few columns: city, street, postcode. First of all, we should join address table to the collection:
1
2
3
4
|
$collection ->joinLeft(
array ( 'sales_flat_order_address' ),
'sales_flat_order.billing_address_id
= sales_flat_order_address.entity_id' ,
array ( 'postcode' , 'street' , 'city' );
|
1
2
3
4
|
addColumn( 'address' , array (
'header' =>
Mage::helper( 'sales' )->__( 'Address' ),
'type' => 'text' ,
));
|
1
2
3
4
5
6
|
addColumn( 'address' , array (
'header' =>
Mage::helper( 'sales' )->__( 'Address' ),
'type' => 'text' ,
'index' => 'city'
'renderer' => 'Atwix_Ordersgrid_Block_Adminhtml_Sales_Order_Renderer_Address'
));
|
1
2
3
4
5
6
7
8
9
10
11
12
|
class Atwix_Ordersgrid_Block_Adminhtml_Sales_Order_Renderer_Address
extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object
$row )
{
$value = $row ->getData( 'city' )
. ',' .
$row ->getData( 'street' )
. ',' .
$row ->getData( 'postcode' );
return $value ;
}
}
|
1
2
3
4
5
6
|
$this ->addColumn( 'address' , array (
'header' =>
Mage::helper( 'sales' )->__( 'Address' ),
'type' => 'text' ,
'renderer' => 'Atwix_Ordersgrid_Block_Adminhtml_Sales_Order_Renderer_Address' ,
'filter_condition_callback' => array ( $this , '_addressFilter' ),
));
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
protected function _addressFilter( $collection , $column )
{
if (! $value = $column ->getFilter()->getValue())
{
return $this ;
}
$this ->getCollection()->getSelect()->where(
"sales_flat_order_address.city
like ?
OR
sales_flat_order_address.street like ?
OR
sales_flat_order_address.postcode like ?"
, "%$value%" );
return $this ;
}
|
As you can see, we are using simple db query condition to filter query results by the columns. This way you can create your own filters for columns with complex values or custom renderers. Feel free to ask any questions and suggest your own improvements.
原文:https://www.atwix.com/magento/grid-filter-for-columns/
PS:在magento的後台grid,用“renderer”來處理最終顯示的內容是很常用的一種做法,但這會帶來一個問題是,經過“renderer”的那一列沒法像普通的列一樣用過濾,這篇文章就是針對這個問題給出了解決方案,而且用的還是原生結構就支持的方式,這裏的關鍵詞就是“filter_condition_callback”,至於為什麼可以這樣用,可以看下Core_Adminhtml_Block_Widget_Grid裏的_addColumnFilterToCollection方法,這裏不再詳細解釋
最後更新:2017-04-03 12:53:43