Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / widgets / grid / ColumnModel.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.grid.ColumnModel
9  * @extends Ext.util.Observable
10  * <p>After the data has been read into the client side cache (<b>{@link Ext.data.Store Store}</b>),
11  * the ColumnModel is used to configure how and what parts of that data will be displayed in the
12  * vertical slices (columns) of the grid. The Ext.grid.ColumnModel Class is the default implementation
13  * of a ColumnModel used by implentations of {@link Ext.grid.GridPanel GridPanel}.</p>
14  * <p>Data is mapped into the store's records and then indexed into the ColumnModel using the
15  * <tt>{@link Ext.grid.Column#dataIndex dataIndex}</tt>:</p>
16  * <pre><code>
17 {data source} == mapping ==> {data store} == <b><tt>{@link Ext.grid.Column#dataIndex dataIndex}</tt></b> ==> {ColumnModel}
18  * </code></pre>
19  * <p>Each {@link Ext.grid.Column Column} in the grid's ColumnModel is configured with a
20  * <tt>{@link Ext.grid.Column#dataIndex dataIndex}</tt> to specify how the data within
21  * each record in the store is indexed into the ColumnModel.</p>
22  * <p>There are two ways to initialize the ColumnModel class:</p>
23  * <p><u>Initialization Method 1: an Array</u></p>
24 <pre><code>
25  var colModel = new Ext.grid.ColumnModel([
26     { header: "Ticker", width: 60, sortable: true},
27     { header: "Company Name", width: 150, sortable: true, id: 'company'},
28     { header: "Market Cap.", width: 100, sortable: true},
29     { header: "$ Sales", width: 100, sortable: true, renderer: money},
30     { header: "Employees", width: 100, sortable: true, resizable: false}
31  ]);
32  </code></pre>
33  * <p>The ColumnModel may be initialized with an Array of {@link Ext.grid.Column} column configuration
34  * objects to define the initial layout / display of the columns in the Grid. The order of each
35  * {@link Ext.grid.Column} column configuration object within the specified Array defines the initial
36  * order of the column display.  A Column's display may be initially hidden using the
37  * <tt>{@link Ext.grid.Column#hidden hidden}</tt></b> config property (and then shown using the column
38  * header menu).  Fields that are not included in the ColumnModel will not be displayable at all.</p>
39  * <p>How each column in the grid correlates (maps) to the {@link Ext.data.Record} field in the
40  * {@link Ext.data.Store Store} the column draws its data from is configured through the
41  * <b><tt>{@link Ext.grid.Column#dataIndex dataIndex}</tt></b>.  If the
42  * <b><tt>{@link Ext.grid.Column#dataIndex dataIndex}</tt></b> is not explicitly defined (as shown in the
43  * example above) it will use the column configuration's index in the Array as the index.</p>
44  * <p>See <b><tt>{@link Ext.grid.Column}</tt></b> for additional configuration options for each column.</p>
45  * <p><u>Initialization Method 2: an Object</u></p>
46  * <p>In order to use configuration options from <tt>Ext.grid.ColumnModel</tt>, an Object may be used to
47  * initialize the ColumnModel.  The column configuration Array will be specified in the <tt><b>{@link #columns}</b></tt>
48  * config property. The <tt><b>{@link #defaults}</b></tt> config property can be used to apply defaults
49  * for all columns, e.g.:</p><pre><code>
50  var colModel = new Ext.grid.ColumnModel({
51     columns: [
52         { header: "Ticker", width: 60, menuDisabled: false},
53         { header: "Company Name", width: 150, id: 'company'},
54         { header: "Market Cap."},
55         { header: "$ Sales", renderer: money},
56         { header: "Employees", resizable: false}
57     ],
58     defaults: {
59         sortable: true,
60         menuDisabled: true,
61         width: 100
62     },
63     listeners: {
64         {@link #hiddenchange}: function(cm, colIndex, hidden) {
65             saveConfig(colIndex, hidden);
66         }
67     }
68 });
69  </code></pre>
70  * <p>In both examples above, the ability to apply a CSS class to all cells in a column (including the
71  * header) is demonstrated through the use of the <b><tt>{@link Ext.grid.Column#id id}</tt></b> config
72  * option. This column could be styled by including the following css:</p><pre><code>
73  //add this css *after* the core css is loaded
74 .x-grid3-td-company {
75     color: red; // entire column will have red font
76 }
77 // modify the header row only, adding an icon to the column header
78 .x-grid3-hd-company {
79     background: transparent
80         url(../../resources/images/icons/silk/building.png)
81         no-repeat 3px 3px ! important;
82         padding-left:20px;
83 }
84  </code></pre>
85  * Note that the "Company Name" column could be specified as the
86  * <b><tt>{@link Ext.grid.GridPanel}.{@link Ext.grid.GridPanel#autoExpandColumn autoExpandColumn}</tt></b>.
87  * @constructor
88  * @param {Mixed} config Specify either an Array of {@link Ext.grid.Column} configuration objects or specify
89  * a configuration Object (see introductory section discussion utilizing Initialization Method 2 above).
90  */
91 Ext.grid.ColumnModel = Ext.extend(Ext.util.Observable, {
92     /**
93      * @cfg {Number} defaultWidth (optional) The width of columns which have no <tt>{@link #width}</tt>
94      * specified (defaults to <tt>100</tt>).  This property shall preferably be configured through the
95      * <tt><b>{@link #defaults}</b></tt> config property.
96      */
97     defaultWidth: 100,
98     /**
99      * @cfg {Boolean} defaultSortable (optional) Default sortable of columns which have no
100      * sortable specified (defaults to <tt>false</tt>).  This property shall preferably be configured
101      * through the <tt><b>{@link #defaults}</b></tt> config property.
102      */
103     defaultSortable: false,
104     /**
105      * @cfg {Array} columns An Array of object literals.  The config options defined by
106      * <b>{@link Ext.grid.Column}</b> are the options which may appear in the object literal for each
107      * individual column definition.
108      */
109     /**
110      * @cfg {Object} defaults Object literal which will be used to apply {@link Ext.grid.Column}
111      * configuration options to all <tt><b>{@link #columns}</b></tt>.  Configuration options specified with
112      * individual {@link Ext.grid.Column column} configs will supersede these <tt><b>{@link #defaults}</b></tt>.
113      */
114     
115     constructor : function(config){
116         /**
117              * An Array of {@link Ext.grid.Column Column definition} objects representing the configuration
118              * of this ColumnModel.  See {@link Ext.grid.Column} for the configuration properties that may
119              * be specified.
120              * @property config
121              * @type Array
122              */
123             if(config.columns){
124                 Ext.apply(this, config);
125                 this.setConfig(config.columns, true);
126             }else{
127                 this.setConfig(config, true);
128             }
129             this.addEvents(
130                 /**
131                  * @event widthchange
132                  * Fires when the width of a column is programmaticially changed using
133                  * <code>{@link #setColumnWidth}</code>.
134                  * Note internal resizing suppresses the event from firing. See also
135                  * {@link Ext.grid.GridPanel}.<code>{@link #columnresize}</code>.
136                  * @param {ColumnModel} this
137                  * @param {Number} columnIndex The column index
138                  * @param {Number} newWidth The new width
139                  */
140                 "widthchange",
141                 /**
142                  * @event headerchange
143                  * Fires when the text of a header changes.
144                  * @param {ColumnModel} this
145                  * @param {Number} columnIndex The column index
146                  * @param {String} newText The new header text
147                  */
148                 "headerchange",
149                 /**
150                  * @event hiddenchange
151                  * Fires when a column is hidden or "unhidden".
152                  * @param {ColumnModel} this
153                  * @param {Number} columnIndex The column index
154                  * @param {Boolean} hidden true if hidden, false otherwise
155                  */
156                 "hiddenchange",
157                 /**
158                  * @event columnmoved
159                  * Fires when a column is moved.
160                  * @param {ColumnModel} this
161                  * @param {Number} oldIndex
162                  * @param {Number} newIndex
163                  */
164                 "columnmoved",
165                 /**
166                  * @event configchange
167                  * Fires when the configuration is changed
168                  * @param {ColumnModel} this
169                  */
170                 "configchange"
171             );
172             Ext.grid.ColumnModel.superclass.constructor.call(this);
173     },
174
175     /**
176      * Returns the id of the column at the specified index.
177      * @param {Number} index The column index
178      * @return {String} the id
179      */
180     getColumnId : function(index){
181         return this.config[index].id;
182     },
183
184     getColumnAt : function(index){
185         return this.config[index];
186     },
187
188     /**
189      * <p>Reconfigures this column model according to the passed Array of column definition objects.
190      * For a description of the individual properties of a column definition object, see the
191      * <a href="#Ext.grid.ColumnModel-configs">Config Options</a>.</p>
192      * <p>Causes the {@link #configchange} event to be fired. A {@link Ext.grid.GridPanel GridPanel}
193      * using this ColumnModel will listen for this event and refresh its UI automatically.</p>
194      * @param {Array} config Array of Column definition objects.
195      * @param {Boolean} initial Specify <tt>true</tt> to bypass cleanup which deletes the <tt>totalWidth</tt>
196      * and destroys existing editors.
197      */
198     setConfig : function(config, initial){
199         var i, c, len;
200         if(!initial){ // cleanup
201             delete this.totalWidth;
202             for(i = 0, len = this.config.length; i < len; i++){
203                 this.config[i].destroy();
204             }
205         }
206
207         // backward compatibility
208         this.defaults = Ext.apply({
209             width: this.defaultWidth,
210             sortable: this.defaultSortable
211         }, this.defaults);
212
213         this.config = config;
214         this.lookup = {};
215
216         for(i = 0, len = config.length; i < len; i++){
217             c = Ext.applyIf(config[i], this.defaults);
218             // if no id, create one using column's ordinal position
219             if(Ext.isEmpty(c.id)){
220                 c.id = i;
221             }
222             if(!c.isColumn){
223                 var Cls = Ext.grid.Column.types[c.xtype || 'gridcolumn'];
224                 c = new Cls(c);
225                 config[i] = c;
226             }
227             this.lookup[c.id] = c;
228         }
229         if(!initial){
230             this.fireEvent('configchange', this);
231         }
232     },
233
234     /**
235      * Returns the column for a specified id.
236      * @param {String} id The column id
237      * @return {Object} the column
238      */
239     getColumnById : function(id){
240         return this.lookup[id];
241     },
242
243     /**
244      * Returns the index for a specified column id.
245      * @param {String} id The column id
246      * @return {Number} the index, or -1 if not found
247      */
248     getIndexById : function(id){
249         for(var i = 0, len = this.config.length; i < len; i++){
250             if(this.config[i].id == id){
251                 return i;
252             }
253         }
254         return -1;
255     },
256
257     /**
258      * Moves a column from one position to another.
259      * @param {Number} oldIndex The index of the column to move.
260      * @param {Number} newIndex The position at which to reinsert the coolumn.
261      */
262     moveColumn : function(oldIndex, newIndex){
263         var c = this.config[oldIndex];
264         this.config.splice(oldIndex, 1);
265         this.config.splice(newIndex, 0, c);
266         this.dataMap = null;
267         this.fireEvent("columnmoved", this, oldIndex, newIndex);
268     },
269
270     /**
271      * Returns the number of columns.
272      * @param {Boolean} visibleOnly Optional. Pass as true to only include visible columns.
273      * @return {Number}
274      */
275     getColumnCount : function(visibleOnly){
276         if(visibleOnly === true){
277             var c = 0;
278             for(var i = 0, len = this.config.length; i < len; i++){
279                 if(!this.isHidden(i)){
280                     c++;
281                 }
282             }
283             return c;
284         }
285         return this.config.length;
286     },
287
288     /**
289      * Returns the column configs that return true by the passed function that is called
290      * with (columnConfig, index)
291 <pre><code>
292 // returns an array of column config objects for all hidden columns
293 var columns = grid.getColumnModel().getColumnsBy(function(c){
294   return c.hidden;
295 });
296 </code></pre>
297      * @param {Function} fn A function which, when passed a {@link Ext.grid.Column Column} object, must
298      * return <code>true</code> if the column is to be included in the returned Array.
299      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function
300      * is executed. Defaults to this ColumnModel.
301      * @return {Array} result
302      */
303     getColumnsBy : function(fn, scope){
304         var r = [];
305         for(var i = 0, len = this.config.length; i < len; i++){
306             var c = this.config[i];
307             if(fn.call(scope||this, c, i) === true){
308                 r[r.length] = c;
309             }
310         }
311         return r;
312     },
313
314     /**
315      * Returns true if the specified column is sortable.
316      * @param {Number} col The column index
317      * @return {Boolean}
318      */
319     isSortable : function(col){
320         return !!this.config[col].sortable;
321     },
322
323     /**
324      * Returns true if the specified column menu is disabled.
325      * @param {Number} col The column index
326      * @return {Boolean}
327      */
328     isMenuDisabled : function(col){
329         return !!this.config[col].menuDisabled;
330     },
331
332     /**
333      * Returns the rendering (formatting) function defined for the column.
334      * @param {Number} col The column index.
335      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
336      */
337     getRenderer : function(col){
338         if(!this.config[col].renderer){
339             return Ext.grid.ColumnModel.defaultRenderer;
340         }
341         return this.config[col].renderer;
342     },
343     
344     getRendererScope : function(col){
345         return this.config[col].scope;
346     },
347
348     /**
349      * Sets the rendering (formatting) function for a column.  See {@link Ext.util.Format} for some
350      * default formatting functions.
351      * @param {Number} col The column index
352      * @param {Function} fn The function to use to process the cell's raw data
353      * to return HTML markup for the grid view. The render function is called with
354      * the following parameters:<ul>
355      * <li><b>value</b> : Object<p class="sub-desc">The data value for the cell.</p></li>
356      * <li><b>metadata</b> : Object<p class="sub-desc">An object in which you may set the following attributes:<ul>
357      * <li><b>css</b> : String<p class="sub-desc">A CSS class name to add to the cell's TD element.</p></li>
358      * <li><b>attr</b> : String<p class="sub-desc">An HTML attribute definition string to apply to the data container element <i>within</i> the table cell
359      * (e.g. 'style="color:red;"').</p></li></ul></p></li>
360      * <li><b>record</b> : Ext.data.record<p class="sub-desc">The {@link Ext.data.Record} from which the data was extracted.</p></li>
361      * <li><b>rowIndex</b> : Number<p class="sub-desc">Row index</p></li>
362      * <li><b>colIndex</b> : Number<p class="sub-desc">Column index</p></li>
363      * <li><b>store</b> : Ext.data.Store<p class="sub-desc">The {@link Ext.data.Store} object from which the Record was extracted.</p></li></ul>
364      */
365     setRenderer : function(col, fn){
366         this.config[col].renderer = fn;
367     },
368
369     /**
370      * Returns the width for the specified column.
371      * @param {Number} col The column index
372      * @return {Number}
373      */
374     getColumnWidth : function(col){
375         return this.config[col].width;
376     },
377
378     /**
379      * Sets the width for a column.
380      * @param {Number} col The column index
381      * @param {Number} width The new width
382      * @param {Boolean} suppressEvent True to suppress firing the <code>{@link #widthchange}</code>
383      * event. Defaults to false.
384      */
385     setColumnWidth : function(col, width, suppressEvent){
386         this.config[col].width = width;
387         this.totalWidth = null;
388         if(!suppressEvent){
389              this.fireEvent("widthchange", this, col, width);
390         }
391     },
392
393     /**
394      * Returns the total width of all columns.
395      * @param {Boolean} includeHidden True to include hidden column widths
396      * @return {Number}
397      */
398     getTotalWidth : function(includeHidden){
399         if(!this.totalWidth){
400             this.totalWidth = 0;
401             for(var i = 0, len = this.config.length; i < len; i++){
402                 if(includeHidden || !this.isHidden(i)){
403                     this.totalWidth += this.getColumnWidth(i);
404                 }
405             }
406         }
407         return this.totalWidth;
408     },
409
410     /**
411      * Returns the header for the specified column.
412      * @param {Number} col The column index
413      * @return {String}
414      */
415     getColumnHeader : function(col){
416         return this.config[col].header;
417     },
418
419     /**
420      * Sets the header for a column.
421      * @param {Number} col The column index
422      * @param {String} header The new header
423      */
424     setColumnHeader : function(col, header){
425         this.config[col].header = header;
426         this.fireEvent("headerchange", this, col, header);
427     },
428
429     /**
430      * Returns the tooltip for the specified column.
431      * @param {Number} col The column index
432      * @return {String}
433      */
434     getColumnTooltip : function(col){
435             return this.config[col].tooltip;
436     },
437     /**
438      * Sets the tooltip for a column.
439      * @param {Number} col The column index
440      * @param {String} tooltip The new tooltip
441      */
442     setColumnTooltip : function(col, tooltip){
443             this.config[col].tooltip = tooltip;
444     },
445
446     /**
447      * Returns the dataIndex for the specified column.
448 <pre><code>
449 // Get field name for the column
450 var fieldName = grid.getColumnModel().getDataIndex(columnIndex);
451 </code></pre>
452      * @param {Number} col The column index
453      * @return {String} The column's dataIndex
454      */
455     getDataIndex : function(col){
456         return this.config[col].dataIndex;
457     },
458
459     /**
460      * Sets the dataIndex for a column.
461      * @param {Number} col The column index
462      * @param {String} dataIndex The new dataIndex
463      */
464     setDataIndex : function(col, dataIndex){
465         this.config[col].dataIndex = dataIndex;
466     },
467
468     /**
469      * Finds the index of the first matching column for the given dataIndex.
470      * @param {String} col The dataIndex to find
471      * @return {Number} The column index, or -1 if no match was found
472      */
473     findColumnIndex : function(dataIndex){
474         var c = this.config;
475         for(var i = 0, len = c.length; i < len; i++){
476             if(c[i].dataIndex == dataIndex){
477                 return i;
478             }
479         }
480         return -1;
481     },
482
483     /**
484      * Returns true if the cell is editable.
485 <pre><code>
486 var store = new Ext.data.Store({...});
487 var colModel = new Ext.grid.ColumnModel({
488   columns: [...],
489   isCellEditable: function(col, row) {
490     var record = store.getAt(row);
491     if (record.get('readonly')) { // replace with your condition
492       return false;
493     }
494     return Ext.grid.ColumnModel.prototype.isCellEditable.call(this, col, row);
495   }
496 });
497 var grid = new Ext.grid.GridPanel({
498   store: store,
499   colModel: colModel,
500   ...
501 });
502 </code></pre>
503      * @param {Number} colIndex The column index
504      * @param {Number} rowIndex The row index
505      * @return {Boolean}
506      */
507     isCellEditable : function(colIndex, rowIndex){
508         var c = this.config[colIndex],
509             ed = c.editable;
510             
511         //force boolean
512         return !!(ed || (!Ext.isDefined(ed) && c.editor));
513     },
514
515     /**
516      * Returns the editor defined for the cell/column.
517      * @param {Number} colIndex The column index
518      * @param {Number} rowIndex The row index
519      * @return {Ext.Editor} The {@link Ext.Editor Editor} that was created to wrap
520      * the {@link Ext.form.Field Field} used to edit the cell.
521      */
522     getCellEditor : function(colIndex, rowIndex){
523         return this.config[colIndex].getCellEditor(rowIndex);
524     },
525
526     /**
527      * Sets if a column is editable.
528      * @param {Number} col The column index
529      * @param {Boolean} editable True if the column is editable
530      */
531     setEditable : function(col, editable){
532         this.config[col].editable = editable;
533     },
534
535     /**
536      * Returns <tt>true</tt> if the column is <code>{@link Ext.grid.Column#hidden hidden}</code>,
537      * <tt>false</tt> otherwise.
538      * @param {Number} colIndex The column index
539      * @return {Boolean}
540      */
541     isHidden : function(colIndex){
542         return !!this.config[colIndex].hidden; // ensure returns boolean
543     },
544
545     /**
546      * Returns <tt>true</tt> if the column is <code>{@link Ext.grid.Column#fixed fixed}</code>,
547      * <tt>false</tt> otherwise.
548      * @param {Number} colIndex The column index
549      * @return {Boolean}
550      */
551     isFixed : function(colIndex){
552         return !!this.config[colIndex].fixed;
553     },
554
555     /**
556      * Returns true if the column can be resized
557      * @return {Boolean}
558      */
559     isResizable : function(colIndex){
560         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
561     },
562     /**
563      * Sets if a column is hidden.
564 <pre><code>
565 myGrid.getColumnModel().setHidden(0, true); // hide column 0 (0 = the first column).
566 </code></pre>
567      * @param {Number} colIndex The column index
568      * @param {Boolean} hidden True if the column is hidden
569      */
570     setHidden : function(colIndex, hidden){
571         var c = this.config[colIndex];
572         if(c.hidden !== hidden){
573             c.hidden = hidden;
574             this.totalWidth = null;
575             this.fireEvent("hiddenchange", this, colIndex, hidden);
576         }
577     },
578
579     /**
580      * Sets the editor for a column and destroys the prior editor.
581      * @param {Number} col The column index
582      * @param {Object} editor The editor object
583      */
584     setEditor : function(col, editor){
585         this.config[col].setEditor(editor);
586     },
587
588     /**
589      * Destroys this column model by purging any event listeners, and removing any editors.
590      */
591     destroy : function(){
592         for(var i = 0, len = this.config.length; i < len; i++){
593             this.config[i].destroy();
594         }
595         this.purgeListeners();
596     }
597 });
598
599 // private
600 Ext.grid.ColumnModel.defaultRenderer = function(value){
601     if(typeof value == "string" && value.length < 1){
602         return "&#160;";
603     }
604     return value;
605 };