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