3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
7 Ext.namespace('Ext.ux.grid');
10 * @class Ext.ux.grid.GridFilters
11 * @extends Ext.util.Observable
12 * <p>GridFilter is a plugin (<code>ptype='gridfilters'</code>) for grids that
13 * allow for a slightly more robust representation of filtering than what is
14 * provided by the default store.</p>
15 * <p>Filtering is adjusted by the user using the grid's column header menu
16 * (this menu can be disabled through configuration). Through this menu users
17 * can configure, enable, and disable filters for each column.</p>
18 * <p><b><u>Features:</u></b></p>
19 * <div class="mdetail-params"><ul>
20 * <li><b>Filtering implementations</b> :
21 * <div class="sub-desc">
22 * Default filtering for Strings, Numeric Ranges, Date Ranges, Lists (which can
23 * be backed by a Ext.data.Store), and Boolean. Additional custom filter types
24 * and menus are easily created by extending Ext.ux.grid.filter.Filter.
26 * <li><b>Graphical indicators</b> :
27 * <div class="sub-desc">
28 * Columns that are filtered have {@link #filterCls a configurable css class}
29 * applied to the column headers.
32 * <div class="sub-desc">
33 * If specified as a plugin to the grid's configured PagingToolbar, the current page
34 * will be reset to page 1 whenever you update the filters.
36 * <li><b>Automatic Reconfiguration</b> :
37 * <div class="sub-desc">
38 * Filters automatically reconfigure when the grid 'reconfigure' event fires.
40 * <li><b>Stateful</b> :
41 * Filter information will be persisted across page loads by specifying a
42 * <code>stateId</code> in the Grid configuration.
43 * <div class="sub-desc">
44 * The filter collection binds to the
45 * <code>{@link Ext.grid.GridPanel#beforestaterestore beforestaterestore}</code>
46 * and <code>{@link Ext.grid.GridPanel#beforestatesave beforestatesave}</code>
47 * events in order to be stateful.
49 * <li><b>Grid Changes</b> :
50 * <div class="sub-desc"><ul>
51 * <li>A <code>filters</code> <i>property</i> is added to the grid pointing to
53 * <li>A <code>filterupdate</code> <i>event</i> is added to the grid and is
54 * fired upon onStateChange completion.</li>
56 * <li><b>Server side code examples</b> :
57 * <div class="sub-desc"><ul>
58 * <li><a href="http://www.vinylfox.com/extjs/grid-filter-php-backend-code.php">PHP</a> - (Thanks VinylFox)</li>
59 * <li><a href="http://extjs.com/forum/showthread.php?p=77326#post77326">Ruby on Rails</a> - (Thanks Zyclops)</li>
60 * <li><a href="http://extjs.com/forum/showthread.php?p=176596#post176596">Ruby on Rails</a> - (Thanks Rotomaul)</li>
61 * <li><a href="http://www.debatablybeta.com/posts/using-extjss-grid-filtering-with-django/">Python</a> - (Thanks Matt)</li>
62 * <li><a href="http://mcantrell.wordpress.com/2008/08/22/extjs-grids-and-grails/">Grails</a> - (Thanks Mike)</li>
65 * <p><b><u>Example usage:</u></b></p>
67 var store = new Ext.data.GroupingStore({
71 var filters = new Ext.ux.grid.GridFilters({
72 autoReload: false, //don't reload automatically
73 local: true, //only filter locally
74 // filters may be configured through the plugin,
75 // or in the column definition within the column model configuration
87 dataIndex: 'dateAdded'
91 options: ['extra small', 'small', 'medium', 'large', 'extra large'],
98 var cm = new Ext.grid.ColumnModel([{
102 var grid = new Ext.grid.GridPanel({
105 view: new Ext.grid.GroupingView(),
109 bbar: new Ext.PagingToolbar({
112 plugins: [filters] //reset page to page 1 if filters change
116 store.load({params: {start: 0, limit: 15}});
118 // a filters property is added to the grid
122 Ext.ux.grid.GridFilters = Ext.extend(Ext.util.Observable, {
124 * @cfg {Boolean} autoReload
125 * Defaults to true, reloading the datasource when a filter change happens.
126 * Set this to false to prevent the datastore from being reloaded if there
127 * are changes to the filters. See <code>{@link updateBuffer}</code>.
131 * @cfg {Boolean} encode
132 * Specify true for {@link #buildQuery} to use Ext.util.JSON.encode to
133 * encode the filter query parameter sent with a remote request.
137 * @cfg {Array} filters
138 * An Array of filters config objects. Refer to each filter type class for
139 * configuration details specific to each filter type. Filters for Strings,
140 * Numeric Ranges, Date Ranges, Lists, and Boolean are the standard filters
144 * @cfg {String} filterCls
145 * The css class to be applied to column headers with active filters.
146 * Defaults to <tt>'ux-filterd-column'</tt>.
148 filterCls : 'ux-filtered-column',
150 * @cfg {Boolean} local
151 * <tt>true</tt> to use Ext.data.Store filter functions (local filtering)
152 * instead of the default (<tt>false</tt>) server side filtering.
156 * @cfg {String} menuFilterText
157 * defaults to <tt>'Filters'</tt>.
159 menuFilterText : 'Filters',
161 * @cfg {String} paramPrefix
162 * The url parameter prefix for the filters.
163 * Defaults to <tt>'filter'</tt>.
165 paramPrefix : 'filter',
167 * @cfg {Boolean} showMenu
168 * Defaults to true, including a filter submenu in the default header menu.
172 * @cfg {String} stateId
173 * Name of the value to be used to store state information.
177 * @cfg {Integer} updateBuffer
178 * Number of milliseconds to defer store updates since the last filter change.
183 constructor : function (config) {
184 config = config || {};
185 this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this);
186 this.filters = new Ext.util.MixedCollection();
187 this.filters.getKey = function (o) {
188 return o ? o.dataIndex : null;
190 this.addFilters(config.filters);
191 delete config.filters;
192 Ext.apply(this, config);
196 init : function (grid) {
197 if (grid instanceof Ext.grid.GridPanel) {
200 this.bindStore(this.grid.getStore(), true);
201 // assumes no filters were passed in the constructor, so try and use ones from the colModel
202 if(this.filters.getCount() == 0){
203 this.addFilters(this.grid.getColumnModel());
206 this.grid.filters = this;
208 this.grid.addEvents({'filterupdate': true});
212 beforestaterestore: this.applyState,
213 beforestatesave: this.saveState,
214 beforedestroy: this.destroy,
215 reconfigure: this.onReconfigure
224 render: this.onRender
228 } else if (grid instanceof Ext.PagingToolbar) {
235 * Handler for the grid's beforestaterestore event (fires before the state of the
237 * @param {Object} grid The grid object
238 * @param {Object} state The hash of state values returned from the StateProvider.
240 applyState : function (grid, state) {
242 this.applyingState = true;
245 for (key in state.filters) {
246 filter = this.filters.get(key);
248 filter.setValue(state.filters[key]);
249 filter.setActive(true);
253 this.deferredUpdate.cancel();
257 delete this.applyingState;
261 * Saves the state of all active filters
262 * @param {Object} grid
263 * @param {Object} state
266 saveState : function (grid, state) {
268 this.filters.each(function (filter) {
270 filters[filter.dataIndex] = filter.getValue();
273 return (state.filters = filters);
278 * Handler called when the grid is rendered
280 onRender : function () {
281 this.grid.getView().on('refresh', this.onRefresh, this);
287 * Handler called by the grid 'beforedestroy' event
289 destroy : function () {
291 this.purgeListeners();
294 Ext.menu.MenuMgr.unregister(this.filterMenu);
295 this.filterMenu.destroy();
296 this.filterMenu = this.menu.menu = null;
301 * Remove all filters, permanently destroying them.
303 removeAll : function () {
305 Ext.destroy.apply(Ext, this.filters.items);
306 // remove all items from the collection
307 this.filters.clear();
313 * Changes the data store bound to this view and refreshes it.
314 * @param {Store} store The store to bind to this view
316 bindStore : function(store, initial){
317 if(!initial && this.store){
319 store.un('load', this.onLoad, this);
321 store.un('beforeload', this.onBeforeLoad, this);
326 store.on('load', this.onLoad, this);
328 store.on('beforeload', this.onBeforeLoad, this);
336 * Handler called when the grid reconfigure event fires
338 onReconfigure : function () {
339 this.bindStore(this.grid.getStore());
340 this.store.clearFilter();
342 this.addFilters(this.grid.getColumnModel());
343 this.updateColumnHeadings();
346 createMenu : function () {
347 var view = this.grid.getView(),
350 if (this.showMenu && hmenu) {
352 this.sep = hmenu.addSeparator();
353 this.filterMenu = new Ext.menu.Menu({
354 id: this.grid.id + '-filters-menu'
356 this.menu = hmenu.add({
359 text: this.menuFilterText,
360 menu: this.filterMenu
365 checkchange: this.onCheckChange,
366 beforecheckchange: this.onBeforeCheck
368 hmenu.on('beforeshow', this.onMenu, this);
370 this.updateColumnHeadings();
375 * Get the filter menu from the filters MixedCollection based on the clicked header
377 getMenuFilter : function () {
378 var view = this.grid.getView();
379 if (!view || view.hdCtxIndex === undefined) {
382 return this.filters.get(
383 view.cm.config[view.hdCtxIndex].dataIndex
389 * Handler called by the grid's hmenu beforeshow event
391 onMenu : function (filterMenu) {
392 var filter = this.getMenuFilter();
398 filter.menu = filter.createMenu();
401 this.menu.menu = filter.menu;
402 this.menu.setChecked(filter.active, false);
403 // disable the menu if filter.disabled explicitly set to true
404 this.menu.setDisabled(filter.disabled === true);
407 this.menu.setVisible(filter !== undefined);
408 this.sep.setVisible(filter !== undefined);
412 onCheckChange : function (item, value) {
413 this.getMenuFilter().setActive(value);
417 onBeforeCheck : function (check, value) {
418 return !value || this.getMenuFilter().isActivatable();
423 * Handler for all events on filters.
424 * @param {String} event Event name
425 * @param {Object} filter Standard signature of the event before the event is fired
427 onStateChange : function (event, filter) {
428 if (event === 'serialize') {
432 if (filter == this.getMenuFilter()) {
433 this.menu.setChecked(filter.active, false);
436 if ((this.autoReload || this.local) && !this.applyingState) {
437 this.deferredUpdate.delay(this.updateBuffer);
439 this.updateColumnHeadings();
441 if (!this.applyingState) {
442 this.grid.saveState();
444 this.grid.fireEvent('filterupdate', this, filter);
449 * Handler for store's beforeload event when configured for remote filtering
450 * @param {Object} store
451 * @param {Object} options
453 onBeforeLoad : function (store, options) {
454 options.params = options.params || {};
455 this.cleanParams(options.params);
456 var params = this.buildQuery(this.getFilterData());
457 Ext.apply(options.params, params);
462 * Handler for store's load event when configured for local filtering
463 * @param {Object} store
464 * @param {Object} options
466 onLoad : function (store, options) {
467 store.filterBy(this.getRecordFilter());
472 * Handler called when the grid's view is refreshed
474 onRefresh : function () {
475 this.updateColumnHeadings();
479 * Update the styles for the header row based on the active filters
481 updateColumnHeadings : function () {
482 var view = this.grid.getView(),
485 for (i = 0, len = view.cm.config.length; i < len; i++) {
486 filter = this.getFilter(view.cm.config[i].dataIndex);
487 Ext.fly(view.getHeaderCell(i))[filter && filter.active ? 'addClass' : 'removeClass'](this.filterCls);
493 reload : function () {
495 this.grid.store.clearFilter(true);
496 this.grid.store.filterBy(this.getRecordFilter());
499 store = this.grid.store;
500 this.deferredUpdate.cancel();
502 start = store.paramNames.start;
503 if (store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) {
504 store.lastOptions.params[start] = 0;
512 * Method factory that generates a record validator for the filters active at the time
516 getRecordFilter : function () {
518 this.filters.each(function (filter) {
525 return function (record) {
526 for (i = 0; i < len; i++) {
527 if (!f[i].validateRecord(record)) {
536 * Adds a filter to the collection and observes it for state change.
537 * @param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object.
538 * @return {Ext.ux.grid.filter.Filter} The existing or newly created filter object.
540 addFilter : function (config) {
541 var Cls = this.getFilterClass(config.type),
542 filter = config.menu ? config : (new Cls(config));
543 this.filters.add(filter);
545 Ext.util.Observable.capture(filter, this.onStateChange, this);
550 * Adds filters to the collection.
551 * @param {Array/Ext.grid.ColumnModel} filters Either an Array of
552 * filter configuration objects or an Ext.grid.ColumnModel. The columns
553 * of a passed Ext.grid.ColumnModel will be examined for a <code>filter</code>
554 * property and, if present, will be used as the filter configuration object.
556 addFilters : function (filters) {
558 var i, len, filter, cm = false, dI;
559 if (filters instanceof Ext.grid.ColumnModel) {
560 filters = filters.config;
563 for (i = 0, len = filters.length; i < len; i++) {
566 dI = filters[i].dataIndex;
567 filter = filters[i].filter || filters[i].filterable;
569 filter = (filter === true) ? {} : filter;
570 Ext.apply(filter, {dataIndex:dI});
571 // filter type is specified in order of preference:
572 // filter type specified in config
573 // type specified in store's field's type config
574 filter.type = filter.type || this.store.fields.get(dI).type;
579 // if filter config found add filter for the column
581 this.addFilter(filter);
588 * Returns a filter for the given dataIndex, if one exists.
589 * @param {String} dataIndex The dataIndex of the desired filter object.
590 * @return {Ext.ux.grid.filter.Filter}
592 getFilter : function (dataIndex) {
593 return this.filters.get(dataIndex);
597 * Turns all filters off. This does not clear the configuration information
598 * (see {@link #removeAll}).
600 clearFilters : function () {
601 this.filters.each(function (filter) {
602 filter.setActive(false);
607 * Returns an Array of the currently active filters.
608 * @return {Array} filters Array of the currently active filters.
610 getFilterData : function () {
611 var filters = [], i, len;
613 this.filters.each(function (f) {
615 var d = [].concat(f.serialize());
616 for (i = 0, len = d.length; i < len; i++) {
628 * Function to take the active filters data and build it into a query.
629 * The format of the query depends on the <code>{@link #encode}</code>
631 * <div class="mdetail-params"><ul>
633 * <li><b><tt>false</tt></b> : <i>Default</i>
634 * <div class="sub-desc">
635 * Flatten into query string of the form (assuming <code>{@link #paramPrefix}='filters'</code>:
637 filters[0][field]="someDataIndex"&
638 filters[0][data][comparison]="someValue1"&
639 filters[0][data][type]="someValue2"&
640 filters[0][data][value]="someValue3"&
643 * <li><b><tt>true</tt></b> :
644 * <div class="sub-desc">
645 * JSON encode the filter data
647 filters[0][field]="someDataIndex"&
648 filters[0][data][comparison]="someValue1"&
649 filters[0][data][type]="someValue2"&
650 filters[0][data][value]="someValue3"&
654 * Override this method to customize the format of the filter query for remote requests.
655 * @param {Array} filters A collection of objects representing active filters and their configuration.
656 * Each element will take the form of {field: dataIndex, data: filterConf}. dataIndex is not assured
657 * to be unique as any one filter may be a composite of more basic filters for the same dataIndex.
658 * @return {Object} Query keys and values
660 buildQuery : function (filters) {
661 var p = {}, i, f, root, dataPrefix, key, tmp,
662 len = filters.length;
665 for (i = 0; i < len; i++) {
667 root = [this.paramPrefix, '[', i, ']'].join('');
668 p[root + '[field]'] = f.field;
670 dataPrefix = root + '[data]';
671 for (key in f.data) {
672 p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
677 for (i = 0; i < len; i++) {
685 // only build if there is active filter
687 p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
694 * Removes filter related query parameters from the provided object.
695 * @param {Object} p Query parameters that may contain filter related fields.
697 cleanParams : function (p) {
698 // if encoding just delete the property
700 delete p[this.paramPrefix];
701 // otherwise scrub the object of filter data
704 regex = new RegExp('^' + this.paramPrefix + '\[[0-9]+\]');
706 if (regex.test(key)) {
714 * Function for locating filter classes, overwrite this with your favorite
715 * loader to provide dynamic filter loading.
716 * @param {String} type The type of filter to load ('Filter' is automatically
717 * appended to the passed type; eg, 'string' becomes 'StringFilter').
718 * @return {Class} The Ext.ux.grid.filter.Class
720 getFilterClass : function (type) {
721 // map the supported Ext.data.Field type values into a supported filter
731 return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter'];
736 Ext.preg('gridfilters', Ext.ux.grid.GridFilters);