Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / examples / ux / gridfilters / GridFilters.js
1 /*!
2  * Ext JS Library 3.2.2
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         delete state.filters;
259     },
260
261     /**
262      * Saves the state of all active filters
263      * @param {Object} grid
264      * @param {Object} state
265      * @return {Boolean}
266      */
267     saveState : function (grid, state) {
268         var filters = {};
269         this.filters.each(function (filter) {
270             if (filter.active) {
271                 filters[filter.dataIndex] = filter.getValue();
272             }
273         });
274         return (state.filters = filters);
275     },
276
277     /**
278      * @private
279      * Handler called when the grid is rendered
280      */
281     onRender : function () {
282         this.grid.getView().on('refresh', this.onRefresh, this);
283         this.createMenu();
284     },
285
286     /**
287      * @private
288      * Handler called by the grid 'beforedestroy' event
289      */
290     destroy : function () {
291         this.removeAll();
292         this.purgeListeners();
293
294         if(this.filterMenu){
295             Ext.menu.MenuMgr.unregister(this.filterMenu);
296             this.filterMenu.destroy();
297              this.filterMenu = this.menu.menu = null;
298         }
299     },
300
301     /**
302      * Remove all filters, permanently destroying them.
303      */
304     removeAll : function () {
305         if(this.filters){
306             Ext.destroy.apply(Ext, this.filters.items);
307             // remove all items from the collection
308             this.filters.clear();
309         }
310     },
311
312
313     /**
314      * Changes the data store bound to this view and refreshes it.
315      * @param {Store} store The store to bind to this view
316      */
317     bindStore : function(store, initial){
318         if(!initial && this.store){
319             if (this.local) {
320                 store.un('load', this.onLoad, this);
321             } else {
322                 store.un('beforeload', this.onBeforeLoad, this);
323             }
324         }
325         if(store){
326             if (this.local) {
327                 store.on('load', this.onLoad, this);
328             } else {
329                 store.on('beforeload', this.onBeforeLoad, this);
330             }
331         }
332         this.store = store;
333     },
334
335     /**
336      * @private
337      * Handler called when the grid reconfigure event fires
338      */
339     onReconfigure : function () {
340         this.bindStore(this.grid.getStore());
341         this.store.clearFilter();
342         this.removeAll();
343         this.addFilters(this.grid.getColumnModel());
344         this.updateColumnHeadings();
345     },
346
347     createMenu : function () {
348         var view = this.grid.getView(),
349             hmenu = view.hmenu;
350
351         if (this.showMenu && hmenu) {
352
353             this.sep  = hmenu.addSeparator();
354             this.filterMenu = new Ext.menu.Menu({
355                 id: this.grid.id + '-filters-menu'
356             });
357             this.menu = hmenu.add({
358                 checked: false,
359                 itemId: 'filters',
360                 text: this.menuFilterText,
361                 menu: this.filterMenu
362             });
363
364             this.menu.on({
365                 scope: this,
366                 checkchange: this.onCheckChange,
367                 beforecheckchange: this.onBeforeCheck
368             });
369             hmenu.on('beforeshow', this.onMenu, this);
370         }
371         this.updateColumnHeadings();
372     },
373
374     /**
375      * @private
376      * Get the filter menu from the filters MixedCollection based on the clicked header
377      */
378     getMenuFilter : function () {
379         var view = this.grid.getView();
380         if (!view || view.hdCtxIndex === undefined) {
381             return null;
382         }
383         return this.filters.get(
384             view.cm.config[view.hdCtxIndex].dataIndex
385         );
386     },
387
388     /**
389      * @private
390      * Handler called by the grid's hmenu beforeshow event
391      */
392     onMenu : function (filterMenu) {
393         var filter = this.getMenuFilter();
394
395         if (filter) {
396 /*
397 TODO: lazy rendering
398             if (!filter.menu) {
399                 filter.menu = filter.createMenu();
400             }
401 */
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);
406         }
407
408         this.menu.setVisible(filter !== undefined);
409         this.sep.setVisible(filter !== undefined);
410     },
411
412     /** @private */
413     onCheckChange : function (item, value) {
414         this.getMenuFilter().setActive(value);
415     },
416
417     /** @private */
418     onBeforeCheck : function (check, value) {
419         return !value || this.getMenuFilter().isActivatable();
420     },
421
422     /**
423      * @private
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
427      */
428     onStateChange : function (event, filter) {
429         if (event === 'serialize') {
430             return;
431         }
432
433         if (filter == this.getMenuFilter()) {
434             this.menu.setChecked(filter.active, false);
435         }
436
437         if ((this.autoReload || this.local) && !this.applyingState) {
438             this.deferredUpdate.delay(this.updateBuffer);
439         }
440         this.updateColumnHeadings();
441
442         if (!this.applyingState) {
443             this.grid.saveState();
444         }
445         this.grid.fireEvent('filterupdate', this, filter);
446     },
447
448     /**
449      * @private
450      * Handler for store's beforeload event when configured for remote filtering
451      * @param {Object} store
452      * @param {Object} options
453      */
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);
459     },
460
461     /**
462      * @private
463      * Handler for store's load event when configured for local filtering
464      * @param {Object} store
465      * @param {Object} options
466      */
467     onLoad : function (store, options) {
468         store.filterBy(this.getRecordFilter());
469     },
470
471     /**
472      * @private
473      * Handler called when the grid's view is refreshed
474      */
475     onRefresh : function () {
476         this.updateColumnHeadings();
477     },
478
479     /**
480      * Update the styles for the header row based on the active filters
481      */
482     updateColumnHeadings : function () {
483         var view = this.grid.getView(),
484             i, len, filter;
485         if (view.mainHd) {
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);
489             }
490         }
491     },
492
493     /** @private */
494     reload : function () {
495         if (this.local) {
496             this.grid.store.clearFilter(true);
497             this.grid.store.filterBy(this.getRecordFilter());
498         } else {
499             var start,
500                 store = this.grid.store;
501             this.deferredUpdate.cancel();
502             if (this.toolbar) {
503                 start = store.paramNames.start;
504                 if (store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) {
505                     store.lastOptions.params[start] = 0;
506                 }
507             }
508             store.reload();
509         }
510     },
511
512     /**
513      * Method factory that generates a record validator for the filters active at the time
514      * of invokation.
515      * @private
516      */
517     getRecordFilter : function () {
518         var f = [], len, i;
519         this.filters.each(function (filter) {
520             if (filter.active) {
521                 f.push(filter);
522             }
523         });
524
525         len = f.length;
526         return function (record) {
527             for (i = 0; i < len; i++) {
528                 if (!f[i].validateRecord(record)) {
529                     return false;
530                 }
531             }
532             return true;
533         };
534     },
535
536     /**
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.
540      */
541     addFilter : function (config) {
542         var Cls = this.getFilterClass(config.type),
543             filter = config.menu ? config : (new Cls(config));
544         this.filters.add(filter);
545
546         Ext.util.Observable.capture(filter, this.onStateChange, this);
547         return filter;
548     },
549
550     /**
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.
556      */
557     addFilters : function (filters) {
558         if (filters) {
559             var i, len, filter, cm = false, dI;
560             if (filters instanceof Ext.grid.ColumnModel) {
561                 filters = filters.config;
562                 cm = true;
563             }
564             for (i = 0, len = filters.length; i < len; i++) {
565                 filter = false;
566                 if (cm) {
567                     dI = filters[i].dataIndex;
568                     filter = filters[i].filter || filters[i].filterable;
569                     if (filter){
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.type;
576                     }
577                 } else {
578                     filter = filters[i];
579                 }
580                 // if filter config found add filter for the column
581                 if (filter) {
582                     this.addFilter(filter);
583                 }
584             }
585         }
586     },
587
588     /**
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}
592      */
593     getFilter : function (dataIndex) {
594         return this.filters.get(dataIndex);
595     },
596
597     /**
598      * Turns all filters off. This does not clear the configuration information
599      * (see {@link #removeAll}).
600      */
601     clearFilters : function () {
602         this.filters.each(function (filter) {
603             filter.setActive(false);
604         });
605     },
606
607     /**
608      * Returns an Array of the currently active filters.
609      * @return {Array} filters Array of the currently active filters.
610      */
611     getFilterData : function () {
612         var filters = [], i, len;
613
614         this.filters.each(function (f) {
615             if (f.active) {
616                 var d = [].concat(f.serialize());
617                 for (i = 0, len = d.length; i < len; i++) {
618                     filters.push({
619                         field: f.dataIndex,
620                         data: d[i]
621                     });
622                 }
623             }
624         });
625         return filters;
626     },
627
628     /**
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>
631      * configuration:
632      * <div class="mdetail-params"><ul>
633      *
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>:
637      * <pre><code>
638 filters[0][field]="someDataIndex"&
639 filters[0][data][comparison]="someValue1"&
640 filters[0][data][type]="someValue2"&
641 filters[0][data][value]="someValue3"&
642      * </code></pre>
643      * </div></li>
644      * <li><b><tt>true</tt></b> :
645      * <div class="sub-desc">
646      * JSON encode the filter data
647      * <pre><code>
648 filters[0][field]="someDataIndex"&
649 filters[0][data][comparison]="someValue1"&
650 filters[0][data][type]="someValue2"&
651 filters[0][data][value]="someValue3"&
652      * </code></pre>
653      * </div></li>
654      * </ul></div>
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
660      */
661     buildQuery : function (filters) {
662         var p = {}, i, f, root, dataPrefix, key, tmp,
663             len = filters.length;
664
665         if (!this.encode){
666             for (i = 0; i < len; i++) {
667                 f = filters[i];
668                 root = [this.paramPrefix, '[', i, ']'].join('');
669                 p[root + '[field]'] = f.field;
670
671                 dataPrefix = root + '[data]';
672                 for (key in f.data) {
673                     p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
674                 }
675             }
676         } else {
677             tmp = [];
678             for (i = 0; i < len; i++) {
679                 f = filters[i];
680                 tmp.push(Ext.apply(
681                     {},
682                     {field: f.field},
683                     f.data
684                 ));
685             }
686             // only build if there is active filter
687             if (tmp.length > 0){
688                 p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
689             }
690         }
691         return p;
692     },
693
694     /**
695      * Removes filter related query parameters from the provided object.
696      * @param {Object} p Query parameters that may contain filter related fields.
697      */
698     cleanParams : function (p) {
699         // if encoding just delete the property
700         if (this.encode) {
701             delete p[this.paramPrefix];
702         // otherwise scrub the object of filter data
703         } else {
704             var regex, key;
705             regex = new RegExp('^' + this.paramPrefix + '\[[0-9]+\]');
706             for (key in p) {
707                 if (regex.test(key)) {
708                     delete p[key];
709                 }
710             }
711         }
712     },
713
714     /**
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
720      */
721     getFilterClass : function (type) {
722         // map the supported Ext.data.Field type values into a supported filter
723         switch(type) {
724             case 'auto':
725               type = 'string';
726               break;
727             case 'int':
728             case 'float':
729               type = 'numeric';
730               break;
731         }
732         return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter'];
733     }
734 });
735
736 // register ptype
737 Ext.preg('gridfilters', Ext.ux.grid.GridFilters);