The below example demonstrates remote data filtering with column headers.
The dropdown options are filled from the grid data and initial filtering is also applied in the load event.
ShipCountry | Customer Name | Order ID | Order Date | Shipping Region | Paid | Shipping Via | Required Date | Shipped Date | Freight | Shipping Name | |
---|---|---|---|---|---|---|---|---|---|---|---|
- | - |
x1
2<div id="grid_filter" style="margin:5px auto;"></div>
3
1361
2$(function () {
3
4function pqDatePicker(ui) {
5var $this = $(this);
6$this
7//.css({ zIndex: 3, position: "relative" })
8.datepicker({
9yearRange: "-25:+0", //25 years prior to present.
10changeYear: true,
11changeMonth: true,
12showButtonPanel: true,
13onClose: function (evt, ui) {
14$(this).focus();
15}
16});
17//default From date
18$this.filter(".pq-from").datepicker("option", "defaultDate", new Date("01/01/1996"));
19//default To date
20$this.filter(".pq-to").datepicker("option", "defaultDate", new Date("12/31/1998"));
21}
22
23//define colModel
24var colM = [
25{ title: "ShipCountry", width: 100, dataIndx: "ShipCountry",
26filter: { type: 'textbox', condition: 'begin', listeners: ['change'] }
27},
28{ title: "Customer Name", width: 120, dataIndx: "ContactName",
29filter: { type: 'textbox', condition: 'begin', listeners: ['change'] }
30},
31{ title: "Order ID", minWidth: 130, dataIndx: "OrderID", dataType: "integer",
32filter: { type: 'textbox', condition: "between", listeners: ['change'] }
33},
34{ title: "Order Date", minWidth: "190", dataIndx: "OrderDate", dataType: "date",
35filter: { type: 'textbox', condition: "between", init: pqDatePicker, listeners: ['change'] }
36},
37{ title: "Shipping Region", width: 130, dataIndx: "ShipRegion",
38filter: { type: 'select',
39condition: 'equal',
40//init: multiSelect,
41valueIndx: "ShipRegion",
42labelIndx: "ShipRegion",
43groupIndx: "ShipCountry",
44prepend: { '': '--Select--' },
45listeners: ['change']
46}
47},
48{ title: "Paid", width: 100, dataIndx: "paid", dataType: "bool", align: "center", type: 'checkbox',
49filter: { type: "checkbox", subtype: 'triple', condition: "equal", listeners: ['click'] }
50},
51{ title: "Shipping Via", width: 140, dataIndx: "ShipVia",
52filter: { type: "select",
53condition: 'equal',
54prepend: { '': '--Select--' },
55valueIndx: "ShipVia",
56labelIndx: "ShipVia",
57listeners: ['change']
58}
59},
60{ title: "Required Date", width: 100, dataIndx: "RequiredDate", dataType: "date" },
61{ title: "Shipped Date", width: 100, dataIndx: "ShippedDate", dataType: "date" },
62{ title: "Freight", width: 100, align: "right", dataIndx: "Freight", dataType: "float" },
63{ title: "Shipping Name", width: 150, dataIndx: "ShipName" },
64{ title: "Shipping Address", width: 270, dataIndx: "ShipAddress" },
65{ title: "Shipping City", width: 100, dataIndx: "ShipCity" },
66{ title: "Shipping Postal Code", width: 180, dataIndx: "ShipPostalCode" }
67
68];
69//define dataModel
70var dataModel = {
71location: "remote",
72dataType: "JSON",
73method: "GET",
74url: "/pro/orders/get"
75//url: "/pro/orders.php",//for PHP
76}
77var obj = {
78height: 500,
79dataModel: dataModel,
80flex:{one: true},
81colModel: colM,
82//pageModel: { type: 'local', rPP: 20 },
83virtualX: true, virtualY: true,
84wrap: false,
85showBottom: false,
86editable: false,
87filterModel: { on: true, mode: "AND", header: true, type: 'remote' },
88title: "Shipping Orders",
89resizable: true,
90hwrap:false,
91freezeCols: 2,
92toolbar:{
93items:[
94{
95type:'button',
96label: 'Toggle filter row',
97listener: function(){
98this.option('filterModel.header', !this.option('filterModel.header'));
99this.refresh();
100}
101},
102{
103type:'button',
104label: 'Reset filters',
105listener: function(){
106this.reset({filter: true});
107}
108}
109]
110}
111};
112var grid = pq.grid( "#grid_filter", obj);
113
114//load shipregion and shipvia dropdowns in first load event.
115grid.one("load", function (evt, ui) {
116var column = grid.getColumn({ dataIndx: "ShipRegion" });
117var filter = column.filter;
118filter.cache = null;
119filter.options = grid.getData({ dataIndx: ["ShipCountry", "ShipRegion"] });
120
121var column = grid.getColumn({ dataIndx: "ShipVia" });
122var filter = column.filter;
123filter.cache = null;
124filter.options = grid.getData({ dataIndx: ["ShipVia"] });
125
126//and apply initial filtering.
127grid.filter({
128oper: 'add',
129data: [
130{ dataIndx: 'ShipRegion', value: 'RJ' },
131{ dataIndx: 'ContactName', value: 'M' }
132]
133});
134});
135});
136
1701
2//model class
3public class OrderCustomer
4{
5[Key]
6public int OrderID { get; set; }
7public String ContactName { get; set; }
8public int EmployeeID { get; set; }
9public DateTime? OrderDate { get; set; }
10public DateTime? RequiredDate { get; set; }
11public DateTime? ShippedDate { get; set; }
12public String ShipVia { get; set; }
13public Decimal Freight { get; set; }//money
14public String ShipName { get; set; }
15public String ShipAddress { get; set; }
16public String ShipCity { get; set; }
17public String ShipRegion { get; set; }
18public String ShipPostalCode { get; set; }
19public String ShipCountry { get; set; }
20public bool paid { get; set; }
21}
22///to check valid column name.
23public class ColumnHelper
24{
25public static bool isValidColumn(String dataIndx)
26{
27if (Regex.IsMatch(dataIndx, "^[a-z,A-Z]*$"))
28{
29return true;
30}
31else
32{
33return false;
34}
35}
36}
37//return type of FitlerHelper.deSerializedFilter
38public struct deSerializedFilter
39{
40public String query;
41public List<Object> param;
42}
43
44public class FilterHelper
45{
46struct Filter
47{
48public String dataIndx;
49public String condition;
50public String value;
51}
52//map to json object posted by client
53struct FilterObj
54{
55public String mode;
56public List<Filter> data;
57}
58public static deSerializedFilter deSerializeFilter(String pq_filter)
59{
60JavaScriptSerializer js = new JavaScriptSerializer();
61
62FilterObj filterObj = js.Deserialize<FilterObj>(pq_filter);
63String mode = filterObj.mode;
64List<Filter> filters = filterObj.data;
65
66List<String> fc = new List<String>();
67
68List<object> param = new List<object>();
69
70foreach (Filter filter in filters)
71{
72String dataIndx = filter.dataIndx;
73if (ColumnHelper.isValidColumn(dataIndx) == false)
74{
75throw new Exception("Invalid column name");
76}
77String text = filter.value;
78String condition = filter.condition;
79if (condition == "contain")
80{
81fc.Add(dataIndx + " like @" + dataIndx);
82param.Add(new SqlParameter(dataIndx, "%" + text + "%"));
83}
84else if (condition == "notcontain")
85{
86fc.Add(dataIndx + " not like @" + dataIndx);
87param.Add(new SqlParameter(dataIndx, "%" + text + "%"));
88}
89else if (condition == "begin")
90{
91fc.Add(dataIndx + " like @" + dataIndx);
92param.Add(new SqlParameter(dataIndx, text + "%"));
93}
94else if (condition == "end")
95{
96fc.Add(dataIndx + " like @" + dataIndx);
97param.Add(new SqlParameter(dataIndx, "%" + text));
98}
99else if (condition == "equal")
100{
101fc.Add(dataIndx + "=@" + dataIndx);
102param.Add(new SqlParameter(dataIndx, text));
103}
104else if (condition == "notequal")
105{
106fc.Add(dataIndx + "!=@" + dataIndx);
107param.Add(new SqlParameter(dataIndx, text));
108}
109else if (condition == "empty")
110{
111fc.Add("isnull(" + dataIndx + ",'')=''");
112//param.Add(new SqlParameter(dataIndx, text + "%"));
113}
114else if (condition == "notempty")
115{
116fc.Add("isnull(" + dataIndx + ",'')!=''");
117}
118else if (condition == "less")
119{
120fc.Add(dataIndx + "<@" + dataIndx);
121param.Add(new SqlParameter(dataIndx, text));
122}
123else if (condition == "great")
124{
125fc.Add(dataIndx + ">@" + dataIndx);
126param.Add(new SqlParameter(dataIndx, text));
127}
128}
129String query = "";
130if (filters.Count > 0)
131{
132query = " where " + String.Join(" " + mode + " ", fc.ToArray());
133}
134
135deSerializedFilter ds = new deSerializedFilter();
136ds.query = query;
137ds.param = param;
138return ds;
139}
140}
141public class ordersController : Controller
142{
143public ActionResult get(String pq_filter)
144{
145pqTestContext db = new pqTestContext();
146
147//filter
148String filterQuery = "";
149List<object> filterParam = new List<object>();
150if (pq_filter != null && pq_filter.Length > 0)
151{
152deSerializedFilter dsf = FilterHelper.deSerializeFilter(pq_filter);
153filterQuery = dsf.query;
154filterParam = dsf.param;
155}
156
157List<OrderCustomer> orders = db.Database.SqlQuery<OrderCustomer>(@"select * from ordercustomers " + filterQuery, filterParam.ToArray()).ToList();
158
159StringBuilder sb = new StringBuilder(@"{""data"":");
160
161JavaScriptSerializer js = new JavaScriptSerializer();
162String json = js.Serialize(orders);
163sb.Append(json);
164
165sb.Append("}");
166
167return this.Content(sb.ToString(), "text/text");
168}
169}
170
1271
2class ColumnHelper
3{
4public static function isValidColumn($dataIndx)
5{
6if (preg_match('/^[a-z,A-Z]*$/', $dataIndx))
7{
8return true;
9}
10else
11{
12return false;
13}
14}
15}
16class FilterHelper
17{
18public static function deSerializeFilter($pq_filter)
19{
20$filterObj = json_decode($pq_filter);
21
22$mode = $filterObj->mode;
23$filters = $filterObj->data;
24
25$fc = array();
26$param= array();
27
28foreach ($filters as $filter)
29{
30$dataIndx = $filter->dataIndx;
31if (ColumnHelper::isValidColumn($dataIndx) == false)
32{
33throw new Exception("Invalid column name");
34}
35$text = $filter->value;
36$condition = $filter->condition;
37
38if ($condition == "contain")
39{
40$fc[] = $dataIndx . " like CONCAT('%', ?, '%')";
41$param[] = $text;
42}
43else if ($condition == "notcontain")
44{
45$fc[] = $dataIndx . " not like CONCAT('%', ?, '%')";
46$param[] = $text;
47}
48else if ($condition == "begin")
49{
50$fc[] = $dataIndx . " like CONCAT( ?, '%')";
51$param[] = $text;
52}
53else if ($condition == "end")
54{
55$fc[] = $dataIndx . " like CONCAT('%', ?)";
56$param[] = $text;
57}
58else if ($condition == "equal")
59{
60$fc[] = $dataIndx . " = ?";
61$param[] = $text;
62}
63else if ($condition == "notequal")
64{
65$fc[] = $dataIndx . " != ?";
66$param[] = $text;
67}
68else if ($condition == "empty")
69{
70$fc[] = "ifnull(" . $dataIndx . ",'')=''";
71}
72else if ($condition == "notempty")
73{
74$fc[] = "ifnull(" . $dataIndx . ",'')!=''";
75}
76else if ($condition == "less")
77{
78$fc[] = $dataIndx . " < ?";
79$param[] = $text;
80}
81else if ($condition == "great")
82{
83$fc[] = $dataIndx . " > ?";
84$param[] = $text;
85}
86}
87$query = "";
88if (sizeof($filters) > 0)
89{
90$query = " where " . join(" ".$mode." ", $fc);
91}
92
93$ds = new stdClass();
94$ds->query = $query;
95$ds->param = $param;
96return $ds;
97}
98}//end of class
99
100
101//orders.php
102$filterQuery = "";
103$filterParam = array();
104if ( isset($_GET["pq_filter"]))
105{
106$pq_filter = $_GET["pq_filter"];
107$dsf = FilterHelper::deSerializeFilter($pq_filter);
108$filterQuery = $dsf->query;
109$filterParam = $dsf->param;
110}
111
112$sql = "Select * from ordercustomers ".$filterQuery;
113
114$dsn = 'mysql:host='.DB_HOSTNAME.';dbname='.DB_NAME;
115$options = array(
116PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
117);
118$dbh = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
119
120$stmt = $dbh->prepare($sql);
121
122$stmt->execute($filterParam);
123
124$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
125
126echo "{\"data\":". json_encode( $rows ) ." }" ;
127
2321
2//ColumnHelper.java
3package helper;
4
5import java.util.regex.*;
6
7/**
8* @author paramvir
9*/
10public class ColumnHelper {
11
12public static boolean isValidColumn(String dataIndx) {
13String pattern = "^[a-z,A-Z]*$";
14
15Pattern r = Pattern.compile(pattern);
16
17Matcher m = r.matcher(dataIndx);
18if (m.find()) {
19return true;
20} else {
21return false;
22}
23}
24}
25//FilterHelper.java
26package helper;
27
28import flexjson.JSONDeserializer;
29import java.text.ParseException;
30import java.text.SimpleDateFormat;
31import java.util.*;
32import java.util.logging.Level;
33import java.util.logging.Logger;
34
35/**
36*
37* @author paramvir
38*/
39public class FilterHelper {
40
41public static Map deSerialize(String pq_filter, String formatDate) {
42JSONDeserializer<Map> deserializer = new JSONDeserializer<Map>();
43
44Map filterObj = deserializer
45.deserialize(pq_filter);
46
47ArrayList<Map> filters = (ArrayList<Map>) filterObj.get("data");
48String mode = (String) filterObj.get("mode");
49
50List<String> fc = new ArrayList<String>();
51
52List<Object> param = new ArrayList<Object>();
53
54for (Map filter : filters) {
55String dataIndx = (String) filter.get("dataIndx");
56if (ColumnHelper.isValidColumn(dataIndx) == false) {
57continue;
58}
59String dataType = (String) filter.get("dataType");
60
61String value = "";
62String value2 = "";
63
64String condition = (String) filter.get("condition");
65
66if (condition.equals("range") == false) {
67value = (String) filter.get("value");
68value2 = (String) filter.get("value2");
69
70value = (value!=null)?value.trim():"";
71value2 = (value2!=null)?value2.trim():"";
72
73if (dataType.equals("bool")) {
74if (value.equals("true")) {
75value = "1";
76} else {
77value = "0";
78}
79}
80else if (dataType.equals("date")) {
81if(value.length()>1){
82value = dateFormat(value, formatDate);
83}
84if(value2.length()>1){
85value2 = dateFormat(value2, formatDate);
86}
87}
88}
89if (condition.equals("contain")) {
90fc.add(dataIndx + " like ?");
91param.add("%" + value + "%");
92} else if (condition.equals("notcontain")) {
93fc.add(dataIndx + " not like ?");
94param.add("%" + value + "%");
95} else if (condition.equals("begin")) {
96fc.add(dataIndx + " like ?");
97param.add(value + "%");
98} else if (condition.equals("end")) {
99fc.add(dataIndx + " like ?");
100param.add("%" + value);
101} else if (condition.equals("equal")) {
102fc.add(dataIndx + "= ?");
103param.add(value);
104} else if (condition.equals("notequal")) {
105fc.add(dataIndx + "!= ?");
106param.add(value);
107} else if (condition.equals("empty")) {
108fc.add("isnull(" + dataIndx + ",'')=''");
109} else if (condition.equals("notempty")) {
110fc.add("isnull(" + dataIndx + ",'')!=''");
111} else if (condition.equals("less")) {
112fc.add(dataIndx + "< ?");
113param.add(value);
114} else if (condition.equals("lte")) {
115fc.add(dataIndx + "<= ?" + dataIndx);
116param.add(value);
117} else if (condition.equals("great")) {
118fc.add(dataIndx + "> ?");
119param.add(value);
120} else if (condition.equals("gte")) {
121fc.add(dataIndx + ">= ?");
122param.add(value);
123} else if (condition.equals("between")) {
124fc.add("(" + dataIndx + ">= ? AND " + dataIndx + "<= ? )");
125param.add(value);
126param.add(value2);
127} else if (condition.equals("range")) {
128List<Object> arrValue = (List<Object>) filter.get("value");
129List<String> fcRange = new ArrayList<String>();
130for (Object val : arrValue) {
131String strVal = (String) val;
132if (strVal == null || strVal.isEmpty()) {
133continue;
134}
135strVal = strVal.trim();
136if (dataType.equals("date")) {
137strVal = dateFormat(strVal, formatDate);
138}
139fcRange.add(dataIndx + "= ?");
140param.add(strVal);
141}
142if (fcRange.size() > 0) {
143fc.add("(" + stringJoin(" OR ", fcRange) + ")");
144}
145}
146}
147String query = "";
148if (fc.size() > 0) {
149query = " where " + stringJoin(" " + mode + " ", fc);
150}
151
152Map ds = new HashMap();
153ds.put("query", query);
154ds.put("param", param);
155return ds;
156}
157private static String dateFormat(String strDate, String format) {
158String newStr ="";
159try {
160Date date = new SimpleDateFormat(format).parse(strDate);
161newStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
162} catch (ParseException ex) {
163Logger.getLogger(FilterHelper.class.getName()).log(Level.SEVERE, null, ex);
164}
165return newStr;
166}
167private static String stringJoin(String connector, List<String> list) {
168String str = "";
169for (int i = 0, len = list.size(); i < len; i++) {
170str += list.get(i);
171if (i < len - 1) {
172str += connector;
173}
174}
175return str;
176}
177}
178//OrdersController.java
179package controller;
180
181import domain.OrderCustomer;
182import flexjson.JSONSerializer;
183import flexjson.transformer.DateTransformer;
184import helper.FilterHelper;
185import helper.SortHelper;
186import java.util.*;
187import org.apache.commons.logging.Log;
188import org.apache.commons.logging.LogFactory;
189import org.springframework.jdbc.core.BeanPropertyRowMapper;
190import org.springframework.jdbc.core.support.JdbcDaoSupport;
191import org.springframework.stereotype.Controller;
192import org.springframework.web.bind.annotation.*;
193
194/**
195* @author paramvir
196*/
197@Controller
198public class OrdersController extends JdbcDaoSupport{
199
200protected final Log logger = LogFactory.getLog(getClass());
201private String formatDate = "MM/dd/yyyy";
202
203@RequestMapping(value="/orders/get",method=RequestMethod.GET)
204public @ResponseBody String get( @RequestParam(required=false) String pq_filter)
205{
206//filter
207String filterQuery = "";
208
209List<Object> filterParam = new ArrayList<Object>();
210if (pq_filter != null && pq_filter.length() > 0)
211{
212Map filterMap = FilterHelper.deSerialize(pq_filter, formatDate);
213filterQuery = (String) filterMap.get("query");
214filterParam = (List<Object>) filterMap.get("param");
215}
216List<OrderCustomer> orders = getJdbcTemplate().query(
217"Select * from ordercustomers " + filterQuery,
218new BeanPropertyRowMapper(OrderCustomer.class)
219, filterParam.toArray()
220);
221
222JSONSerializer serializer = new JSONSerializer().exclude("*.class");
223String json = serializer
224.transform(new DateTransformer(formatDate), Date.class)
225.serialize(orders);
226
227String sb="{\"data\":"+json+"}";
228
229return sb;
230}
231}
232