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;
258 delete state.filters;
262 * Saves the state of all active filters
263 * @param {Object} grid
264 * @param {Object} state
267 saveState : function (grid, state) {
269 this.filters.each(function (filter) {
271 filters[filter.dataIndex] = filter.getValue();
274 return (state.filters = filters);
279 * Handler called when the grid is rendered
281 onRender : function () {
282 this.grid.getView().on('refresh', this.onRefresh, this);
288 * Handler called by the grid 'beforedestroy' event
290 destroy : function () {
292 this.purgeListeners();
295 Ext.menu.MenuMgr.unregister(this.filterMenu);
296 this.filterMenu.destroy();
297 this.filterMenu = this.menu.menu = null;
302 * Remove all filters, permanently destroying them.
304 removeAll : function () {
306 Ext.destroy.apply(Ext, this.filters.items);
307 // remove all items from the collection
308 this.filters.clear();
314 * Changes the data store bound to this view and refreshes it.
315 * @param {Store} store The store to bind to this view
317 bindStore : function(store, initial){
318 if(!initial && this.store){
320 store.un('load', this.onLoad, this);
322 store.un('beforeload', this.onBeforeLoad, this);
327 store.on('load', this.onLoad, this);
329 store.on('beforeload', this.onBeforeLoad, this);
337 * Handler called when the grid reconfigure event fires
339 onReconfigure : function () {
340 this.bindStore(this.grid.getStore());
341 this.store.clearFilter();
343 this.addFilters(this.grid.getColumnModel());
344 this.updateColumnHeadings();
347 createMenu : function () {
348 var view = this.grid.getView(),
351 if (this.showMenu && hmenu) {
353 this.sep = hmenu.addSeparator();
354 this.filterMenu = new Ext.menu.Menu({
355 id: this.grid.id + '-filters-menu'
357 this.menu = hmenu.add({
360 text: this.menuFilterText,
361 menu: this.filterMenu
366 checkchange: this.onCheckChange,
367 beforecheckchange: this.onBeforeCheck
369 hmenu.on('beforeshow', this.onMenu, this);
371 this.updateColumnHeadings();
376 * Get the filter menu from the filters MixedCollection based on the clicked header
378 getMenuFilter : function () {
379 var view = this.grid.getView();
380 if (!view || view.hdCtxIndex === undefined) {
383 return this.filters.get(
384 view.cm.config[view.hdCtxIndex].dataIndex
390 * Handler called by the grid's hmenu beforeshow event
392 onMenu : function (filterMenu) {
393 var filter = this.getMenuFilter();
399 filter.menu = filter.createMenu();
402 this.menu.menu = filter.menu;
403 this.menu.setChecked(filter.active, false);
404 // disable the menu if filter.disabled explicitly set to true
405 this.menu.setDisabled(filter.disabled === true);
408 this.menu.setVisible(filter !== undefined);
409 this.sep.setVisible(filter !== undefined);
413 onCheckChange : function (item, value) {
414 this.getMenuFilter().setActive(value);
418 onBeforeCheck : function (check, value) {
419 return !value || this.getMenuFilter().isActivatable();
424 * Handler for all events on filters.
425 * @param {String} event Event name
426 * @param {Object} filter Standard signature of the event before the event is fired
428 onStateChange : function (event, filter) {
429 if (event === 'serialize') {
433 if (filter == this.getMenuFilter()) {
434 this.menu.setChecked(filter.active, false);
437 if ((this.autoReload || this.local) && !this.applyingState) {
438 this.deferredUpdate.delay(this.updateBuffer);
440 this.updateColumnHeadings();
442 if (!this.applyingState) {
443 this.grid.saveState();
445 this.grid.fireEvent('filterupdate', this, filter);
450 * Handler for store's beforeload event when configured for remote filtering
451 * @param {Object} store
452 * @param {Object} options
454 onBeforeLoad : function (store, options) {
455 options.params = options.params || {};
456 this.cleanParams(options.params);
457 var params = this.buildQuery(this.getFilterData());
458 Ext.apply(options.params, params);
463 * Handler for store's load event when configured for local filtering
464 * @param {Object} store
465 * @param {Object} options
467 onLoad : function (store, options) {
468 store.filterBy(this.getRecordFilter());
473 * Handler called when the grid's view is refreshed
475 onRefresh : function () {
476 this.updateColumnHeadings();
480 * Update the styles for the header row based on the active filters
482 updateColumnHeadings : function () {
483 var view = this.grid.getView(),
486 for (i = 0, len = view.cm.config.length; i < len; i++) {
487 filter = this.getFilter(view.cm.config[i].dataIndex);
488 Ext.fly(view.getHeaderCell(i))[filter && filter.active ? 'addClass' : 'removeClass'](this.filterCls);
494 reload : function () {
496 this.grid.store.clearFilter(true);
497 this.grid.store.filterBy(this.getRecordFilter());
500 store = this.grid.store;
501 this.deferredUpdate.cancel();
503 start = store.paramNames.start;
504 if (store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) {
505 store.lastOptions.params[start] = 0;
513 * Method factory that generates a record validator for the filters active at the time
517 getRecordFilter : function () {
519 this.filters.each(function (filter) {
526 return function (record) {
527 for (i = 0; i < len; i++) {
528 if (!f[i].validateRecord(record)) {
537 * Adds a filter to the collection and observes it for state change.
538 * @param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object.
539 * @return {Ext.ux.grid.filter.Filter} The existing or newly created filter object.
541 addFilter : function (config) {
542 var Cls = this.getFilterClass(config.type),
543 filter = config.menu ? config : (new Cls(config));
544 this.filters.add(filter);
546 Ext.util.Observable.capture(filter, this.onStateChange, this);
551 * Adds filters to the collection.
552 * @param {Array/Ext.grid.ColumnModel} filters Either an Array of
553 * filter configuration objects or an Ext.grid.ColumnModel. The columns
554 * of a passed Ext.grid.ColumnModel will be examined for a <code>filter</code>
555 * property and, if present, will be used as the filter configuration object.
557 addFilters : function (filters) {
559 var i, len, filter, cm = false, dI;
560 if (filters instanceof Ext.grid.ColumnModel) {
561 filters = filters.config;
564 for (i = 0, len = filters.length; i < len; i++) {
567 dI = filters[i].dataIndex;
568 filter = filters[i].filter || filters[i].filterable;
570 filter = (filter === true) ? {} : filter;
571 Ext.apply(filter, {dataIndex:dI});
572 // filter type is specified in order of preference:
573 // filter type specified in config
574 // type specified in store's field's type config
575 filter.type = filter.type || this.store.fields.get(dI).type;
580 // if filter config found add filter for the column
582 this.addFilter(filter);
589 * Returns a filter for the given dataIndex, if one exists.
590 * @param {String} dataIndex The dataIndex of the desired filter object.
591 * @return {Ext.ux.grid.filter.Filter}
593 getFilter : function (dataIndex) {
594 return this.filters.get(dataIndex);
598 * Turns all filters off. This does not clear the configuration information
599 * (see {@link #removeAll}).
601 clearFilters : function () {
602 this.filters.each(function (filter) {
603 filter.setActive(false);
608 * Returns an Array of the currently active filters.
609 * @return {Array} filters Array of the currently active filters.
611 getFilterData : function () {
612 var filters = [], i, len;
614 this.filters.each(function (f) {
616 var d = [].concat(f.serialize());
617 for (i = 0, len = d.length; i < len; i++) {
629 * Function to take the active filters data and build it into a query.
630 * The format of the query depends on the <code>{@link #encode}</code>
632 * <div class="mdetail-params"><ul>
634 * <li><b><tt>false</tt></b> : <i>Default</i>
635 * <div class="sub-desc">
636 * Flatten into query string of the form (assuming <code>{@link #paramPrefix}='filters'</code>:
638 filters[0][field]="someDataIndex"&
639 filters[0][data][comparison]="someValue1"&
640 filters[0][data][type]="someValue2"&
641 filters[0][data][value]="someValue3"&
644 * <li><b><tt>true</tt></b> :
645 * <div class="sub-desc">
646 * JSON encode the filter data
648 filters[0][field]="someDataIndex"&
649 filters[0][data][comparison]="someValue1"&
650 filters[0][data][type]="someValue2"&
651 filters[0][data][value]="someValue3"&
655 * Override this method to customize the format of the filter query for remote requests.
656 * @param {Array} filters A collection of objects representing active filters and their configuration.
657 * Each element will take the form of {field: dataIndex, data: filterConf}. dataIndex is not assured
658 * to be unique as any one filter may be a composite of more basic filters for the same dataIndex.
659 * @return {Object} Query keys and values
661 buildQuery : function (filters) {
662 var p = {}, i, f, root, dataPrefix, key, tmp,
663 len = filters.length;
666 for (i = 0; i < len; i++) {
668 root = [this.paramPrefix, '[', i, ']'].join('');
669 p[root + '[field]'] = f.field;
671 dataPrefix = root + '[data]';
672 for (key in f.data) {
673 p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
678 for (i = 0; i < len; i++) {
686 // only build if there is active filter
688 p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
695 * Removes filter related query parameters from the provided object.
696 * @param {Object} p Query parameters that may contain filter related fields.
698 cleanParams : function (p) {
699 // if encoding just delete the property
701 delete p[this.paramPrefix];
702 // otherwise scrub the object of filter data
705 regex = new RegExp('^' + this.paramPrefix + '\[[0-9]+\]');
707 if (regex.test(key)) {
715 * Function for locating filter classes, overwrite this with your favorite
716 * loader to provide dynamic filter loading.
717 * @param {String} type The type of filter to load ('Filter' is automatically
718 * appended to the passed type; eg, 'string' becomes 'StringFilter').
719 * @return {Class} The Ext.ux.grid.filter.Class
721 getFilterClass : function (type) {
722 // map the supported Ext.data.Field type values into a supported filter
732 return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter'];
737 Ext.preg('gridfilters', Ext.ux.grid.GridFilters);