Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / docs / source / GroupingView.html
1 <html>
2 <head>
3   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
4   <title>The source code</title>
5     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
6     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
7 </head>
8 <body  onload="prettyPrint();">
9     <pre class="prettyprint lang-js">/*!
10  * Ext JS Library 3.2.2
11  * Copyright(c) 2006-2010 Ext JS, Inc.
12  * licensing@extjs.com
13  * http://www.extjs.com/license
14  */
15 <div id="cls-Ext.grid.GroupingView"></div>/**
16  * @class Ext.grid.GroupingView
17  * @extends Ext.grid.GridView
18  * Adds the ability for single level grouping to the grid. A {@link Ext.data.GroupingStore GroupingStore}
19  * must be used to enable grouping.  Some grouping characteristics may also be configured at the
20  * {@link Ext.grid.Column Column level}<div class="mdetail-params"><ul>
21  * <li><code>{@link Ext.grid.Column#emptyGroupText emptyGroupText}</code></li>
22  * <li><code>{@link Ext.grid.Column#groupable groupable}</code></li>
23  * <li><code>{@link Ext.grid.Column#groupName groupName}</code></li>
24  * <li><code>{@link Ext.grid.Column#groupRender groupRender}</code></li>
25  * </ul></div>
26  * <p>Sample usage:</p>
27  * <pre><code>
28 var grid = new Ext.grid.GridPanel({
29     // A groupingStore is required for a GroupingView
30     store: new {@link Ext.data.GroupingStore}({
31         autoDestroy: true,
32         reader: reader,
33         data: xg.dummyData,
34         sortInfo: {field: 'company', direction: 'ASC'},
35         {@link Ext.data.GroupingStore#groupOnSort groupOnSort}: true,
36         {@link Ext.data.GroupingStore#remoteGroup remoteGroup}: true,
37         {@link Ext.data.GroupingStore#groupField groupField}: 'industry'
38     }),
39     colModel: new {@link Ext.grid.ColumnModel}({
40         columns:[
41             {id:'company',header: 'Company', width: 60, dataIndex: 'company'},
42             // {@link Ext.grid.Column#groupable groupable}, {@link Ext.grid.Column#groupName groupName}, {@link Ext.grid.Column#groupRender groupRender} are also configurable at column level
43             {header: 'Price', renderer: Ext.util.Format.usMoney, dataIndex: 'price', {@link Ext.grid.Column#groupable groupable}: false},
44             {header: 'Change', dataIndex: 'change', renderer: Ext.util.Format.usMoney},
45             {header: 'Industry', dataIndex: 'industry'},
46             {header: 'Last Updated', renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
47         ],
48         defaults: {
49             sortable: true,
50             menuDisabled: false,
51             width: 20
52         }
53     }),
54
55     view: new Ext.grid.GroupingView({
56         {@link Ext.grid.GridView#forceFit forceFit}: true,
57         // custom grouping text template to display the number of items per group
58         {@link #groupTextTpl}: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
59     }),
60
61     frame:true,
62     width: 700,
63     height: 450,
64     collapsible: true,
65     animCollapse: false,
66     title: 'Grouping Example',
67     iconCls: 'icon-grid',
68     renderTo: document.body
69 });
70  * </code></pre>
71  * @constructor
72  * @param {Object} config
73  */
74 Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, {
75
76     <div id="cfg-Ext.grid.GroupingView-groupByText"></div>/**
77      * @cfg {String} groupByText Text displayed in the grid header menu for grouping by a column
78      * (defaults to 'Group By This Field').
79      */
80     groupByText : 'Group By This Field',
81     <div id="cfg-Ext.grid.GroupingView-showGroupsText"></div>/**
82      * @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping
83      * (defaults to 'Show in Groups').
84      */
85     showGroupsText : 'Show in Groups',
86     <div id="cfg-Ext.grid.GroupingView-hideGroupedColumn"></div>/**
87      * @cfg {Boolean} hideGroupedColumn <tt>true</tt> to hide the column that is currently grouped (defaults to <tt>false</tt>)
88      */
89     hideGroupedColumn : false,
90     <div id="cfg-Ext.grid.GroupingView-showGroupName"></div>/**
91      * @cfg {Boolean} showGroupName If <tt>true</tt> will display a prefix plus a ': ' before the group field value
92      * in the group header line.  The prefix will consist of the <tt><b>{@link Ext.grid.Column#groupName groupName}</b></tt>
93      * (or the configured <tt><b>{@link Ext.grid.Column#header header}</b></tt> if not provided) configured in the
94      * {@link Ext.grid.Column} for each set of grouped rows (defaults to <tt>true</tt>).
95      */
96     showGroupName : true,
97     <div id="cfg-Ext.grid.GroupingView-startCollapsed"></div>/**
98      * @cfg {Boolean} startCollapsed <tt>true</tt> to start all groups collapsed (defaults to <tt>false</tt>)
99      */
100     startCollapsed : false,
101     <div id="cfg-Ext.grid.GroupingView-enableGrouping"></div>/**
102      * @cfg {Boolean} enableGrouping <tt>false</tt> to disable grouping functionality (defaults to <tt>true</tt>)
103      */
104     enableGrouping : true,
105     <div id="cfg-Ext.grid.GroupingView-enableGroupingMenu"></div>/**
106      * @cfg {Boolean} enableGroupingMenu <tt>true</tt> to enable the grouping control in the column menu (defaults to <tt>true</tt>)
107      */
108     enableGroupingMenu : true,
109     <div id="cfg-Ext.grid.GroupingView-enableNoGroups"></div>/**
110      * @cfg {Boolean} enableNoGroups <tt>true</tt> to allow the user to turn off grouping (defaults to <tt>true</tt>)
111      */
112     enableNoGroups : true,
113     <div id="cfg-Ext.grid.GroupingView-emptyGroupText"></div>/**
114      * @cfg {String} emptyGroupText The text to display when there is an empty group value (defaults to <tt>'(None)'</tt>).
115      * May also be specified per column, see {@link Ext.grid.Column}.{@link Ext.grid.Column#emptyGroupText emptyGroupText}.
116      */
117     emptyGroupText : '(None)',
118     <div id="cfg-Ext.grid.GroupingView-ignoreAdd"></div>/**
119      * @cfg {Boolean} ignoreAdd <tt>true</tt> to skip refreshing the view when new rows are added (defaults to <tt>false</tt>)
120      */
121     ignoreAdd : false,
122     <div id="cfg-Ext.grid.GroupingView-groupTextTpl"></div>/**
123      * @cfg {String} groupTextTpl The template used to render the group header (defaults to <tt>'{text}'</tt>).
124      * This is used to format an object which contains the following properties:
125      * <div class="mdetail-params"><ul>
126      * <li><b>group</b> : String<p class="sub-desc">The <i>rendered</i> value of the group field.
127      * By default this is the unchanged value of the group field. If a <tt><b>{@link Ext.grid.Column#groupRenderer groupRenderer}</b></tt>
128      * is specified, it is the result of a call to that function.</p></li>
129      * <li><b>gvalue</b> : Object<p class="sub-desc">The <i>raw</i> value of the group field.</p></li>
130      * <li><b>text</b> : String<p class="sub-desc">The configured header (as described in <tt>{@link #showGroupName})</tt>
131      * if <tt>{@link #showGroupName}</tt> is <tt>true</tt>) plus the <i>rendered</i> group field value.</p></li>
132      * <li><b>groupId</b> : String<p class="sub-desc">A unique, generated ID which is applied to the
133      * View Element which contains the group.</p></li>
134      * <li><b>startRow</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li>
135      * <li><b>rs</b> : Array<p class="sub-desc">Contains a single element: The Record providing the data
136      * for the row which caused group change.</p></li>
137      * <li><b>cls</b> : String<p class="sub-desc">The generated class name string to apply to the group header Element.</p></li>
138      * <li><b>style</b> : String<p class="sub-desc">The inline style rules to apply to the group header Element.</p></li>
139      * </ul></div></p>
140      * See {@link Ext.XTemplate} for information on how to format data using a template. Possible usage:<pre><code>
141 var grid = new Ext.grid.GridPanel({
142     ...
143     view: new Ext.grid.GroupingView({
144         groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
145     }),
146 });
147      * </code></pre>
148      */
149     groupTextTpl : '{text}',
150
151     <div id="cfg-Ext.grid.GroupingView-groupMode"></div>/**
152      * @cfg {String} groupMode Indicates how to construct the group identifier. <tt>'value'</tt> constructs the id using
153      * raw value, <tt>'display'</tt> constructs the id using the rendered value. Defaults to <tt>'value'</tt>.
154      */
155     groupMode: 'value',
156
157     <div id="cfg-Ext.grid.GroupingView-groupRenderer"></div>/**
158      * @cfg {Function} groupRenderer This property must be configured in the {@link Ext.grid.Column} for
159      * each column.
160      */
161
162     // private
163     initTemplates : function(){
164         Ext.grid.GroupingView.superclass.initTemplates.call(this);
165         this.state = {};
166
167         var sm = this.grid.getSelectionModel();
168         sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect',
169                 this.onBeforeRowSelect, this);
170
171         if(!this.startGroup){
172             this.startGroup = new Ext.XTemplate(
173                 '<div id="{groupId}" class="x-grid-group {cls}">',
174                     '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div class="x-grid-group-title">', this.groupTextTpl ,'</div></div>',
175                     '<div id="{groupId}-bd" class="x-grid-group-body">'
176             );
177         }
178         this.startGroup.compile();
179
180         if (!this.endGroup) {
181             this.endGroup = '</div></div>';
182         }
183     },
184
185     // private
186     findGroup : function(el){
187         return Ext.fly(el).up('.x-grid-group', this.mainBody.dom);
188     },
189
190     // private
191     getGroups : function(){
192         return this.hasRows() ? this.mainBody.dom.childNodes : [];
193     },
194
195     // private
196     onAdd : function(ds, records, index) {
197         if (this.canGroup() && !this.ignoreAdd) {
198             var ss = this.getScrollState();
199             this.fireEvent('beforerowsinserted', ds, index, index + (records.length-1));
200             this.refresh();
201             this.restoreScroll(ss);
202             this.fireEvent('rowsinserted', ds, index, index + (records.length-1));
203         } else if (!this.canGroup()) {
204             Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments);
205         }
206     },
207
208     // private
209     onRemove : function(ds, record, index, isUpdate){
210         Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments);
211         var g = document.getElementById(record._groupId);
212         if(g && g.childNodes[1].childNodes.length < 1){
213             Ext.removeNode(g);
214         }
215         this.applyEmptyText();
216     },
217
218     // private
219     refreshRow : function(record){
220         if(this.ds.getCount()==1){
221             this.refresh();
222         }else{
223             this.isUpdating = true;
224             Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments);
225             this.isUpdating = false;
226         }
227     },
228
229     // private
230     beforeMenuShow : function(){
231         var item, items = this.hmenu.items, disabled = this.cm.config[this.hdCtxIndex].groupable === false;
232         if((item = items.get('groupBy'))){
233             item.setDisabled(disabled);
234         }
235         if((item = items.get('showGroups'))){
236             item.setDisabled(disabled);
237             item.setChecked(this.canGroup(), true);
238         }
239     },
240
241     // private
242     renderUI : function(){
243         Ext.grid.GroupingView.superclass.renderUI.call(this);
244         this.mainBody.on('mousedown', this.interceptMouse, this);
245
246         if(this.enableGroupingMenu && this.hmenu){
247             this.hmenu.add('-',{
248                 itemId:'groupBy',
249                 text: this.groupByText,
250                 handler: this.onGroupByClick,
251                 scope: this,
252                 iconCls:'x-group-by-icon'
253             });
254             if(this.enableNoGroups){
255                 this.hmenu.add({
256                     itemId:'showGroups',
257                     text: this.showGroupsText,
258                     checked: true,
259                     checkHandler: this.onShowGroupsClick,
260                     scope: this
261                 });
262             }
263             this.hmenu.on('beforeshow', this.beforeMenuShow, this);
264         }
265     },
266
267     processEvent: function(name, e){
268         Ext.grid.GroupingView.superclass.processEvent.call(this, name, e);
269         var hd = e.getTarget('.x-grid-group-hd', this.mainBody);
270         if(hd){
271             // group value is at the end of the string
272             var field = this.getGroupField(),
273                 prefix = this.getPrefix(field),
274                 groupValue = hd.id.substring(prefix.length),
275                 emptyRe = new RegExp('gp-' + Ext.escapeRe(field) + '--hd');
276
277             // remove trailing '-hd'
278             groupValue = groupValue.substr(0, groupValue.length - 3);
279             
280             // also need to check for empty groups
281             if(groupValue || emptyRe.test(hd.id)){
282                 this.grid.fireEvent('group' + name, this.grid, field, groupValue, e);
283             }
284             if(name == 'mousedown' && e.button == 0){
285                 this.toggleGroup(hd.parentNode);
286             }
287         }
288
289     },
290
291     // private
292     onGroupByClick : function(){
293         this.enableGrouping = true;
294         this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));
295         this.grid.fireEvent('groupchange', this, this.grid.store.getGroupState());
296         this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups
297         this.refresh();
298     },
299
300     // private
301     onShowGroupsClick : function(mi, checked){
302         this.enableGrouping = checked;
303         if(checked){
304             this.onGroupByClick();
305         }else{
306             this.grid.store.clearGrouping();
307             this.grid.fireEvent('groupchange', this, null);
308         }
309     },
310
311     <div id="method-Ext.grid.GroupingView-toggleRowIndex"></div>/**
312      * Toggle the group that contains the specific row.
313      * @param {Number} rowIndex The row inside the group
314      * @param {Boolean} expanded (optional)
315      */
316     toggleRowIndex : function(rowIndex, expanded){
317         if(!this.canGroup()){
318             return;
319         }
320         var row = this.getRow(rowIndex);
321         if(row){
322             this.toggleGroup(this.findGroup(row), expanded);
323         }
324     },
325
326     <div id="method-Ext.grid.GroupingView-toggleGroup"></div>/**
327      * Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed.
328      * @param {String} groupId The groupId assigned to the group (see getGroupId)
329      * @param {Boolean} expanded (optional)
330      */
331     toggleGroup : function(group, expanded){
332         var gel = Ext.get(group);
333         expanded = Ext.isDefined(expanded) ? expanded : gel.hasClass('x-grid-group-collapsed');
334         if(this.state[gel.id] !== expanded){
335             this.grid.stopEditing(true);
336             this.state[gel.id] = expanded;
337             gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed');
338         }
339     },
340
341     <div id="method-Ext.grid.GroupingView-toggleAllGroups"></div>/**
342      * Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed.
343      * @param {Boolean} expanded (optional)
344      */
345     toggleAllGroups : function(expanded){
346         var groups = this.getGroups();
347         for(var i = 0, len = groups.length; i < len; i++){
348             this.toggleGroup(groups[i], expanded);
349         }
350     },
351
352     <div id="method-Ext.grid.GroupingView-expandAllGroups"></div>/**
353      * Expands all grouped rows.
354      */
355     expandAllGroups : function(){
356         this.toggleAllGroups(true);
357     },
358
359     <div id="method-Ext.grid.GroupingView-collapseAllGroups"></div>/**
360      * Collapses all grouped rows.
361      */
362     collapseAllGroups : function(){
363         this.toggleAllGroups(false);
364     },
365
366     // private
367     interceptMouse : function(e){
368         var hd = e.getTarget('.x-grid-group-hd', this.mainBody);
369         if(hd){
370             e.stopEvent();
371             this.toggleGroup(hd.parentNode);
372         }
373     },
374
375     // private
376     getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){
377         var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v);
378         if(g === '' || g === '&#160;'){
379             g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText;
380         }
381         return g;
382     },
383
384     // private
385     getGroupField : function(){
386         return this.grid.store.getGroupState();
387     },
388
389     // private
390     afterRender : function(){
391         if(!this.ds || !this.cm){
392             return;
393         }
394         Ext.grid.GroupingView.superclass.afterRender.call(this);
395         if(this.grid.deferRowRender){
396             this.updateGroupWidths();
397         }
398     },
399
400     // private
401     renderRows : function(){
402         var groupField = this.getGroupField();
403         var eg = !!groupField;
404         // if they turned off grouping and the last grouped field is hidden
405         if(this.hideGroupedColumn) {
406             var colIndex = this.cm.findColumnIndex(groupField),
407                 hasLastGroupField = Ext.isDefined(this.lastGroupField);
408             if(!eg && hasLastGroupField){
409                 this.mainBody.update('');
410                 this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false);
411                 delete this.lastGroupField;
412             }else if (eg && !hasLastGroupField){
413                 this.lastGroupField = groupField;
414                 this.cm.setHidden(colIndex, true);
415             }else if (eg && hasLastGroupField && groupField !== this.lastGroupField) {
416                 this.mainBody.update('');
417                 var oldIndex = this.cm.findColumnIndex(this.lastGroupField);
418                 this.cm.setHidden(oldIndex, false);
419                 this.lastGroupField = groupField;
420                 this.cm.setHidden(colIndex, true);
421             }
422         }
423         return Ext.grid.GroupingView.superclass.renderRows.apply(
424                     this, arguments);
425     },
426
427     // private
428     doRender : function(cs, rs, ds, startRow, colCount, stripe){
429         if(rs.length < 1){
430             return '';
431         }
432
433         if(!this.canGroup() || this.isUpdating){
434             return Ext.grid.GroupingView.superclass.doRender.apply(this, arguments);
435         }
436
437         var groupField = this.getGroupField(),
438             colIndex = this.cm.findColumnIndex(groupField),
439             g,
440             gstyle = 'width:' + this.getTotalWidth() + ';',
441             cfg = this.cm.config[colIndex],
442             groupRenderer = cfg.groupRenderer || cfg.renderer,
443             prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : '',
444             groups = [],
445             curGroup, i, len, gid;
446
447         for(i = 0, len = rs.length; i < len; i++){
448             var rowIndex = startRow + i,
449                 r = rs[i],
450                 gvalue = r.data[groupField];
451
452                 g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds);
453             if(!curGroup || curGroup.group != g){
454                 gid = this.constructId(gvalue, groupField, colIndex);
455                 // if state is defined use it, however state is in terms of expanded
456                 // so negate it, otherwise use the default.
457                 this.state[gid] = !(Ext.isDefined(this.state[gid]) ? !this.state[gid] : this.startCollapsed);
458                 curGroup = {
459                     group: g,
460                     gvalue: gvalue,
461                     text: prefix + g,
462                     groupId: gid,
463                     startRow: rowIndex,
464                     rs: [r],
465                     cls: this.state[gid] ? '' : 'x-grid-group-collapsed',
466                     style: gstyle
467                 };
468                 groups.push(curGroup);
469             }else{
470                 curGroup.rs.push(r);
471             }
472             r._groupId = gid;
473         }
474
475         var buf = [];
476         for(i = 0, len = groups.length; i < len; i++){
477             g = groups[i];
478             this.doGroupStart(buf, g, cs, ds, colCount);
479             buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call(
480                     this, cs, g.rs, ds, g.startRow, colCount, stripe);
481
482             this.doGroupEnd(buf, g, cs, ds, colCount);
483         }
484         return buf.join('');
485     },
486
487     <div id="method-Ext.grid.GroupingView-getGroupId"></div>/**
488      * Dynamically tries to determine the groupId of a specific value
489      * @param {String} value
490      * @return {String} The group id
491      */
492     getGroupId : function(value){
493         var field = this.getGroupField();
494         return this.constructId(value, field, this.cm.findColumnIndex(field));
495     },
496
497     // private
498     constructId : function(value, field, idx){
499         var cfg = this.cm.config[idx],
500             groupRenderer = cfg.groupRenderer || cfg.renderer,
501             val = (this.groupMode == 'value') ? value : this.getGroup(value, {data:{}}, groupRenderer, 0, idx, this.ds);
502
503         return this.getPrefix(field) + Ext.util.Format.htmlEncode(val);
504     },
505
506     // private
507     canGroup  : function(){
508         return this.enableGrouping && !!this.getGroupField();
509     },
510
511     // private
512     getPrefix: function(field){
513         return this.grid.getGridEl().id + '-gp-' + field + '-';
514     },
515
516     // private
517     doGroupStart : function(buf, g, cs, ds, colCount){
518         buf[buf.length] = this.startGroup.apply(g);
519     },
520
521     // private
522     doGroupEnd : function(buf, g, cs, ds, colCount){
523         buf[buf.length] = this.endGroup;
524     },
525
526     // private
527     getRows : function(){
528         if(!this.canGroup()){
529             return Ext.grid.GroupingView.superclass.getRows.call(this);
530         }
531         var r = [],
532             gs = this.getGroups(),
533             g,
534             i = 0,
535             len = gs.length,
536             j,
537             jlen;
538         for(; i < len; ++i){
539             g = gs[i].childNodes[1];
540             if(g){
541                 g = g.childNodes;
542                 for(j = 0, jlen = g.length; j < jlen; ++j){
543                     r[r.length] = g[j];
544                 }
545             }
546         }
547         return r;
548     },
549
550     // private
551     updateGroupWidths : function(){
552         if(!this.canGroup() || !this.hasRows()){
553             return;
554         }
555         var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.getScrollOffset()) +'px';
556         var gs = this.getGroups();
557         for(var i = 0, len = gs.length; i < len; i++){
558             gs[i].firstChild.style.width = tw;
559         }
560     },
561
562     // private
563     onColumnWidthUpdated : function(col, w, tw){
564         Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this, col, w, tw);
565         this.updateGroupWidths();
566     },
567
568     // private
569     onAllColumnWidthsUpdated : function(ws, tw){
570         Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this, ws, tw);
571         this.updateGroupWidths();
572     },
573
574     // private
575     onColumnHiddenUpdated : function(col, hidden, tw){
576         Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this, col, hidden, tw);
577         this.updateGroupWidths();
578     },
579
580     // private
581     onLayout : function(){
582         this.updateGroupWidths();
583     },
584
585     // private
586     onBeforeRowSelect : function(sm, rowIndex){
587         this.toggleRowIndex(rowIndex, true);
588     }
589 });
590 // private
591 Ext.grid.GroupingView.GROUP_ID = 1000;</pre>    
592 </body>
593 </html>