Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / examples / ux / gridfilters / GridFilters.js
1 /*!
2  * Ext JS Library 3.2.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 Ext.namespace('Ext.ux.grid');
8
9 /**
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.
25  * </div></li>
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.
30  * </div></li>
31  * <li><b>Paging</b> :
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.
35  * </div></li>
36  * <li><b>Automatic Reconfiguration</b> :
37  * <div class="sub-desc">
38  * Filters automatically reconfigure when the grid 'reconfigure' event fires.
39  * </div></li>
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.
48  * </div></li>
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
52  * this plugin.</li>
53  * <li>A <code>filterupdate</code> <i>event</i> is added to the grid and is
54  * fired upon onStateChange completion.</li>
55  * </ul></div></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>
63  * </ul></div></li>
64  * </ul></div>
65  * <p><b><u>Example usage:</u></b></p>
66  * <pre><code>
67 var store = new Ext.data.GroupingStore({
68     ...
69 });
70
71 var filters = new Ext.ux.grid.GridFilters({
72     autoReload: false, //don&#39;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
76     filters: [{
77         type: 'numeric',
78         dataIndex: 'id'
79     }, {
80         type: 'string',
81         dataIndex: 'name'
82     }, {
83         type: 'numeric',
84         dataIndex: 'price'
85     }, {
86         type: 'date',
87         dataIndex: 'dateAdded'
88     }, {
89         type: 'list',
90         dataIndex: 'size',
91         options: ['extra small', 'small', 'medium', 'large', 'extra large'],
92         phpMode: true
93     }, {
94         type: 'boolean',
95         dataIndex: 'visible'
96     }]
97 });
98 var cm = new Ext.grid.ColumnModel([{
99     ...
100 }]);
101
102 var grid = new Ext.grid.GridPanel({
103      ds: store,
104      cm: cm,
105      view: new Ext.grid.GroupingView(),
106      plugins: [filters],
107      height: 400,
108      width: 700,
109      bbar: new Ext.PagingToolbar({
110          store: store,
111          pageSize: 15,
112          plugins: [filters] //reset page to page 1 if filters change
113      })
114  });
115
116 store.load({params: {start: 0, limit: 15}});
117
118 // a filters property is added to the grid
119 grid.filters
120  * </code></pre>
121  */
122 Ext.ux.grid.GridFilters = Ext.extend(Ext.util.Observable, {
123     /**
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>.
128      */
129     autoReload : true,
130     /**
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.
134      * Defaults to false.
135      */
136     /**
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
141      * available.
142      */
143     /**
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>.
147      */
148     filterCls : 'ux-filtered-column',
149     /**
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.
153      */
154     local : false,
155     /**
156      * @cfg {String} menuFilterText
157      * defaults to <tt>'Filters'</tt>.
158      */
159     menuFilterText : 'Filters',
160     /**
161      * @cfg {String} paramPrefix
162      * The url parameter prefix for the filters.
163      * Defaults to <tt>'filter'</tt>.
164      */
165     paramPrefix : 'filter',
166     /**
167      * @cfg {Boolean} showMenu
168      * Defaults to true, including a filter submenu in the default header menu.
169      */
170     showMenu : true,
171     /**
172      * @cfg {String} stateId
173      * Name of the value to be used to store state information.
174      */
175     stateId : undefined,
176     /**
177      * @cfg {Integer} updateBuffer
178      * Number of milliseconds to defer store updates since the last filter change.
179      */
180     updateBuffer : 500,
181
182     /** @private */
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;
189         };
190         this.addFilters(config.filters);
191         delete config.filters;
192         Ext.apply(this, config);
193     },
194
195     /** @private */
196     init : function (grid) {
197         if (grid instanceof Ext.grid.GridPanel) {
198             this.grid = grid;
199
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());
204             }
205
206             this.grid.filters = this;
207
208             this.grid.addEvents({'filterupdate': true});
209
210             grid.on({
211                 scope: this,
212                 beforestaterestore: this.applyState,
213                 beforestatesave: this.saveState,
214                 beforedestroy: this.destroy,
215                 reconfigure: this.onReconfigure
216             });
217
218             if (grid.rendered){
219                 this.onRender();
220             } else {
221                 grid.on({
222                     scope: this,
223                     single: true,
224                     render: this.onRender
225                 });
226             }
227
228         } else if (grid instanceof Ext.PagingToolbar) {
229             this.toolbar = grid;
230         }
231     },
232
233     /**
234      * @private
235      * Handler for the grid's beforestaterestore event (fires before the state of the
236      * grid is restored).
237      * @param {Object} grid The grid object
238      * @param {Object} state The hash of state values returned from the StateProvider.
239      */
240     applyState : function (grid, state) {
241         var key, filter;
242         this.applyingState = true;
243         this.clearFilters();
244         if (state.filters) {
245             for (key in state.filters) {
246                 filter = this.filters.get(key);
247                 if (filter) {
248                     filter.setValue(state.filters[key]);
249                     filter.setActive(true);
250                 }
251             }
252         }
253         this.deferredUpdate.cancel();
254         if (this.local) {
255             this.reload();
256         }
257         delete this.applyingState;
258     },
259
260     /**
261      * Saves the state of all active filters
262      * @param {Object} grid
263      * @param {Object} state
264      * @return {Boolean}
265      */
266     saveState : function (grid, state) {
267         var filters = {};
268         this.filters.each(function (filter) {
269             if (filter.active) {
270                 filters[filter.dataIndex] = filter.getValue();
271             }
272         });
273         return (state.filters = filters);
274     },
275
276     /**
277      * @private
278      * Handler called when the grid is rendered
279      */
280     onRender : function () {
281         this.grid.getView().on('refresh', this.onRefresh, this);
282         this.createMenu();
283     },
284
285     /**
286      * @private
287      * Handler called by the grid 'beforedestroy' event
288      */
289     destroy : function () {
290         this.removeAll();
291         this.purgeListeners();
292
293         if(this.filterMenu){
294             Ext.menu.MenuMgr.unregister(this.filterMenu);
295             this.filterMenu.destroy();
296              this.filterMenu = this.menu.menu = null;
297         }
298     },
299
300     /**
301      * Remove all filters, permanently destroying them.
302      */
303     removeAll : function () {
304         if(this.filters){
305             Ext.destroy.apply(Ext, this.filters.items);
306             // remove all items from the collection
307             this.filters.clear();
308         }
309     },
310
311
312     /**
313      * Changes the data store bound to this view and refreshes it.
314      * @param {Store} store The store to bind to this view
315      */
316     bindStore : function(store, initial){
317         if(!initial && this.store){
318             if (this.local) {
319                 store.un('load', this.onLoad, this);
320             } else {
321                 store.un('beforeload', this.onBeforeLoad, this);
322             }
323         }
324         if(store){
325             if (this.local) {
326                 store.on('load', this.onLoad, this);
327             } else {
328                 store.on('beforeload', this.onBeforeLoad, this);
329             }
330         }
331         this.store = store;
332     },
333
334     /**
335      * @private
336      * Handler called when the grid reconfigure event fires
337      */
338     onReconfigure : function () {
339         this.bindStore(this.grid.getStore());
340         this.store.clearFilter();
341         this.removeAll();
342         this.addFilters(this.grid.getColumnModel());
343         this.updateColumnHeadings();
344     },
345
346     createMenu : function () {
347         var view = this.grid.getView(),
348             hmenu = view.hmenu;
349
350         if (this.showMenu && hmenu) {
351
352             this.sep  = hmenu.addSeparator();
353             this.filterMenu = new Ext.menu.Menu({
354                 id: this.grid.id + '-filters-menu'
355             });
356             this.menu = hmenu.add({
357                 checked: false,
358                 itemId: 'filters',
359                 text: this.menuFilterText,
360                 menu: this.filterMenu
361             });
362
363             this.menu.on({
364                 scope: this,
365                 checkchange: this.onCheckChange,
366                 beforecheckchange: this.onBeforeCheck
367             });
368             hmenu.on('beforeshow', this.onMenu, this);
369         }
370         this.updateColumnHeadings();
371     },
372
373     /**
374      * @private
375      * Get the filter menu from the filters MixedCollection based on the clicked header
376      */
377     getMenuFilter : function () {
378         var view = this.grid.getView();
379         if (!view || view.hdCtxIndex === undefined) {
380             return null;
381         }
382         return this.filters.get(
383             view.cm.config[view.hdCtxIndex].dataIndex
384         );
385     },
386
387     /**
388      * @private
389      * Handler called by the grid's hmenu beforeshow event
390      */
391     onMenu : function (filterMenu) {
392         var filter = this.getMenuFilter();
393
394         if (filter) {
395 /*
396 TODO: lazy rendering
397             if (!filter.menu) {
398                 filter.menu = filter.createMenu();
399             }
400 */
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);
405         }
406
407         this.menu.setVisible(filter !== undefined);
408         this.sep.setVisible(filter !== undefined);
409     },
410
411     /** @private */
412     onCheckChange : function (item, value) {
413         this.getMenuFilter().setActive(value);
414     },
415
416     /** @private */
417     onBeforeCheck : function (check, value) {
418         return !value || this.getMenuFilter().isActivatable();
419     },
420
421     /**
422      * @private
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
426      */
427     onStateChange : function (event, filter) {
428         if (event === 'serialize') {
429             return;
430         }
431
432         if (filter == this.getMenuFilter()) {
433             this.menu.setChecked(filter.active, false);
434         }
435
436         if ((this.autoReload || this.local) && !this.applyingState) {
437             this.deferredUpdate.delay(this.updateBuffer);
438         }
439         this.updateColumnHeadings();
440
441         if (!this.applyingState) {
442             this.grid.saveState();
443         }
444         this.grid.fireEvent('filterupdate', this, filter);
445     },
446
447     /**
448      * @private
449      * Handler for store's beforeload event when configured for remote filtering
450      * @param {Object} store
451      * @param {Object} options
452      */
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);
458     },
459
460     /**
461      * @private
462      * Handler for store's load event when configured for local filtering
463      * @param {Object} store
464      * @param {Object} options
465      */
466     onLoad : function (store, options) {
467         store.filterBy(this.getRecordFilter());
468     },
469
470     /**
471      * @private
472      * Handler called when the grid's view is refreshed
473      */
474     onRefresh : function () {
475         this.updateColumnHeadings();
476     },
477
478     /**
479      * Update the styles for the header row based on the active filters
480      */
481     updateColumnHeadings : function () {
482         var view = this.grid.getView(),
483             i, len, filter;
484         if (view.mainHd) {
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);
488             }
489         }
490     },
491
492     /** @private */
493     reload : function () {
494         if (this.local) {
495             this.grid.store.clearFilter(true);
496             this.grid.store.filterBy(this.getRecordFilter());
497         } else {
498             var start,
499                 store = this.grid.store;
500             this.deferredUpdate.cancel();
501             if (this.toolbar) {
502                 start = store.paramNames.start;
503                 if (store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) {
504                     store.lastOptions.params[start] = 0;
505                 }
506             }
507             store.reload();
508         }
509     },
510
511     /**
512      * Method factory that generates a record validator for the filters active at the time
513      * of invokation.
514      * @private
515      */
516     getRecordFilter : function () {
517         var f = [], len, i;
518         this.filters.each(function (filter) {
519             if (filter.active) {
520                 f.push(filter);
521             }
522         });
523
524         len = f.length;
525         return function (record) {
526             for (i = 0; i < len; i++) {
527                 if (!f[i].validateRecord(record)) {
528                     return false;
529                 }
530             }
531             return true;
532         };
533     },
534
535     /**
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.
539      */
540     addFilter : function (config) {
541         var Cls = this.getFilterClass(config.type),
542             filter = config.menu ? config : (new Cls(config));
543         this.filters.add(filter);
544
545         Ext.util.Observable.capture(filter, this.onStateChange, this);
546         return filter;
547     },
548
549     /**
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.
555      */
556     addFilters : function (filters) {
557         if (filters) {
558             var i, len, filter, cm = false, dI;
559             if (filters instanceof Ext.grid.ColumnModel) {
560                 filters = filters.config;
561                 cm = true;
562             }
563             for (i = 0, len = filters.length; i < len; i++) {
564                 filter = false;
565                 if (cm) {
566                     dI = filters[i].dataIndex;
567                     filter = filters[i].filter || filters[i].filterable;
568                     if (filter){
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;
575                     }
576                 } else {
577                     filter = filters[i];
578                 }
579                 // if filter config found add filter for the column
580                 if (filter) {
581                     this.addFilter(filter);
582                 }
583             }
584         }
585     },
586
587     /**
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}
591      */
592     getFilter : function (dataIndex) {
593         return this.filters.get(dataIndex);
594     },
595
596     /**
597      * Turns all filters off. This does not clear the configuration information
598      * (see {@link #removeAll}).
599      */
600     clearFilters : function () {
601         this.filters.each(function (filter) {
602             filter.setActive(false);
603         });
604     },
605
606     /**
607      * Returns an Array of the currently active filters.
608      * @return {Array} filters Array of the currently active filters.
609      */
610     getFilterData : function () {
611         var filters = [], i, len;
612
613         this.filters.each(function (f) {
614             if (f.active) {
615                 var d = [].concat(f.serialize());
616                 for (i = 0, len = d.length; i < len; i++) {
617                     filters.push({
618                         field: f.dataIndex,
619                         data: d[i]
620                     });
621                 }
622             }
623         });
624         return filters;
625     },
626
627     /**
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>
630      * configuration:
631      * <div class="mdetail-params"><ul>
632      *
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>:
636      * <pre><code>
637 filters[0][field]="someDataIndex"&
638 filters[0][data][comparison]="someValue1"&
639 filters[0][data][type]="someValue2"&
640 filters[0][data][value]="someValue3"&
641      * </code></pre>
642      * </div></li>
643      * <li><b><tt>true</tt></b> :
644      * <div class="sub-desc">
645      * JSON encode the filter data
646      * <pre><code>
647 filters[0][field]="someDataIndex"&
648 filters[0][data][comparison]="someValue1"&
649 filters[0][data][type]="someValue2"&
650 filters[0][data][value]="someValue3"&
651      * </code></pre>
652      * </div></li>
653      * </ul></div>
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
659      */
660     buildQuery : function (filters) {
661         var p = {}, i, f, root, dataPrefix, key, tmp,
662             len = filters.length;
663
664         if (!this.encode){
665             for (i = 0; i < len; i++) {
666                 f = filters[i];
667                 root = [this.paramPrefix, '[', i, ']'].join('');
668                 p[root + '[field]'] = f.field;
669
670                 dataPrefix = root + '[data]';
671                 for (key in f.data) {
672                     p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
673                 }
674             }
675         } else {
676             tmp = [];
677             for (i = 0; i < len; i++) {
678                 f = filters[i];
679                 tmp.push(Ext.apply(
680                     {},
681                     {field: f.field},
682                     f.data
683                 ));
684             }
685             // only build if there is active filter
686             if (tmp.length > 0){
687                 p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
688             }
689         }
690         return p;
691     },
692
693     /**
694      * Removes filter related query parameters from the provided object.
695      * @param {Object} p Query parameters that may contain filter related fields.
696      */
697     cleanParams : function (p) {
698         // if encoding just delete the property
699         if (this.encode) {
700             delete p[this.paramPrefix];
701         // otherwise scrub the object of filter data
702         } else {
703             var regex, key;
704             regex = new RegExp('^' + this.paramPrefix + '\[[0-9]+\]');
705             for (key in p) {
706                 if (regex.test(key)) {
707                     delete p[key];
708                 }
709             }
710         }
711     },
712
713     /**
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
719      */
720     getFilterClass : function (type) {
721         // map the supported Ext.data.Field type values into a supported filter
722         switch(type) {
723             case 'auto':
724               type = 'string';
725               break;
726             case 'int':
727             case 'float':
728               type = 'numeric';
729               break;
730         }
731         return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter'];
732     }
733 });
734
735 // register ptype
736 Ext.preg('gridfilters', Ext.ux.grid.GridFilters);