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