Fix #6864 - dynamicall adding columns
[roojs1] / Roo / grid / ColumnModel.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12
13 /**
14  * @class Roo.grid.ColumnModel
15  * @extends Roo.util.Observable
16  * This is the default implementation of a ColumnModel used by the Grid. It defines
17  * the columns in the grid.
18  * <br>Usage:<br>
19  <pre><code>
20  var colModel = new Roo.grid.ColumnModel([
21         {header: "Ticker", width: 60, sortable: true, locked: true},
22         {header: "Company Name", width: 150, sortable: true},
23         {header: "Market Cap.", width: 100, sortable: true},
24         {header: "$ Sales", width: 100, sortable: true, renderer: money},
25         {header: "Employees", width: 100, sortable: true, resizable: false}
26  ]);
27  </code></pre>
28  * <p>
29  
30  * The config options listed for this class are options which may appear in each
31  * individual column definition.
32  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
33  * @constructor
34  * @param {Object} config An Array of column config objects. See this class's
35  * config objects for details.
36 */
37 Roo.grid.ColumnModel = function(config){
38         /**
39      * The config passed into the constructor
40      */
41     this.config = []; //config;
42     this.lookup = {};
43
44     // if no id, create one
45     // if the column does not have a dataIndex mapping,
46     // map it to the order it is in the config
47     for(var i = 0, len = config.length; i < len; i++){
48         this.addColumn(config[i]);
49         
50     }
51
52     /**
53      * The width of columns which have no width specified (defaults to 100)
54      * @type Number
55      */
56     this.defaultWidth = 100;
57
58     /**
59      * Default sortable of columns which have no sortable specified (defaults to false)
60      * @type Boolean
61      */
62     this.defaultSortable = false;
63
64     this.addEvents({
65         /**
66              * @event widthchange
67              * Fires when the width of a column changes.
68              * @param {ColumnModel} this
69              * @param {Number} columnIndex The column index
70              * @param {Number} newWidth The new width
71              */
72             "widthchange": true,
73         /**
74              * @event headerchange
75              * Fires when the text of a header changes.
76              * @param {ColumnModel} this
77              * @param {Number} columnIndex The column index
78              * @param {Number} newText The new header text
79              */
80             "headerchange": true,
81         /**
82              * @event hiddenchange
83              * Fires when a column is hidden or "unhidden".
84              * @param {ColumnModel} this
85              * @param {Number} columnIndex The column index
86              * @param {Boolean} hidden true if hidden, false otherwise
87              */
88             "hiddenchange": true,
89             /**
90          * @event columnmoved
91          * Fires when a column is moved.
92          * @param {ColumnModel} this
93          * @param {Number} oldIndex
94          * @param {Number} newIndex
95          */
96         "columnmoved" : true,
97         /**
98          * @event columlockchange
99          * Fires when a column's locked state is changed
100          * @param {ColumnModel} this
101          * @param {Number} colIndex
102          * @param {Boolean} locked true if locked
103          */
104         "columnlockchange" : true
105     });
106     Roo.grid.ColumnModel.superclass.constructor.call(this);
107 };
108 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
109     /**
110      * @cfg {String} header The header text to display in the Grid view.
111      */
112     /**
113      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
114      * {@link Roo.data.Record} definition from which to draw the column's value. If not
115      * specified, the column's index is used as an index into the Record's data Array.
116      */
117     /**
118      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
119      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
120      */
121     /**
122      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
123      * Defaults to the value of the {@link #defaultSortable} property.
124      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
125      */
126     /**
127      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
128      */
129     /**
130      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
131      */
132     /**
133      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
134      */
135     /**
136      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
137      */
138     /**
139      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
140      * given the cell's data value. See {@link #setRenderer}. If not specified, the
141      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
142      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
143      */
144        /**
145      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
146      */
147     /**
148      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
149      */
150     /**
151      * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined.
152      */
153     /**
154      * @cfg {String} cursor (Optional)
155      */
156     /**
157      * @cfg {String} tooltip (Optional)
158      */
159     /**
160      * @cfg {Number} xs (Optional)
161      */
162     /**
163      * @cfg {Number} sm (Optional)
164      */
165     /**
166      * @cfg {Number} md (Optional)
167      */
168     /**
169      * @cfg {Number} lg (Optional)
170      */
171     /**
172      * Returns the id of the column at the specified index.
173      * @param {Number} index The column index
174      * @return {String} the id
175      */
176     getColumnId : function(index){
177         return this.config[index].id;
178     },
179
180     /**
181      * Returns the column for a specified id.
182      * @param {String} id The column id
183      * @return {Object} the column
184      */
185     getColumnById : function(id){
186         return this.lookup[id];
187     },
188
189     
190     /**
191      * Returns the column Object for a specified dataIndex.
192      * @param {String} dataIndex The column dataIndex
193      * @return {Object|Boolean} the column or false if not found
194      */
195     getColumnByDataIndex: function(dataIndex){
196         var index = this.findColumnIndex(dataIndex);
197         return index > -1 ? this.config[index] : false;
198     },
199     
200     /**
201      * Returns the index for a specified column id.
202      * @param {String} id The column id
203      * @return {Number} the index, or -1 if not found
204      */
205     getIndexById : function(id){
206         for(var i = 0, len = this.config.length; i < len; i++){
207             if(this.config[i].id == id){
208                 return i;
209             }
210         }
211         return -1;
212     },
213     
214     /**
215      * Returns the index for a specified column dataIndex.
216      * @param {String} dataIndex The column dataIndex
217      * @return {Number} the index, or -1 if not found
218      */
219     
220     findColumnIndex : function(dataIndex){
221         for(var i = 0, len = this.config.length; i < len; i++){
222             if(this.config[i].dataIndex == dataIndex){
223                 return i;
224             }
225         }
226         return -1;
227     },
228     
229     
230     moveColumn : function(oldIndex, newIndex){
231         var c = this.config[oldIndex];
232         this.config.splice(oldIndex, 1);
233         this.config.splice(newIndex, 0, c);
234         this.dataMap = null;
235         this.fireEvent("columnmoved", this, oldIndex, newIndex);
236     },
237
238     isLocked : function(colIndex){
239         return this.config[colIndex].locked === true;
240     },
241
242     setLocked : function(colIndex, value, suppressEvent){
243         if(this.isLocked(colIndex) == value){
244             return;
245         }
246         this.config[colIndex].locked = value;
247         if(!suppressEvent){
248             this.fireEvent("columnlockchange", this, colIndex, value);
249         }
250     },
251
252     getTotalLockedWidth : function(){
253         var totalWidth = 0;
254         for(var i = 0; i < this.config.length; i++){
255             if(this.isLocked(i) && !this.isHidden(i)){
256                 this.totalWidth += this.getColumnWidth(i);
257             }
258         }
259         return totalWidth;
260     },
261
262     getLockedCount : function(){
263         for(var i = 0, len = this.config.length; i < len; i++){
264             if(!this.isLocked(i)){
265                 return i;
266             }
267         }
268         
269         return this.config.length;
270     },
271
272     /**
273      * Returns the number of columns.
274      * @return {Number}
275      */
276     getColumnCount : function(visibleOnly){
277         if(visibleOnly === true){
278             var c = 0;
279             for(var i = 0, len = this.config.length; i < len; i++){
280                 if(!this.isHidden(i)){
281                     c++;
282                 }
283             }
284             return c;
285         }
286         return this.config.length;
287     },
288
289     /**
290      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
291      * @param {Function} fn
292      * @param {Object} scope (optional)
293      * @return {Array} result
294      */
295     getColumnsBy : function(fn, scope){
296         var r = [];
297         for(var i = 0, len = this.config.length; i < len; i++){
298             var c = this.config[i];
299             if(fn.call(scope||this, c, i) === true){
300                 r[r.length] = c;
301             }
302         }
303         return r;
304     },
305
306     /**
307      * Returns true if the specified column is sortable.
308      * @param {Number} col The column index
309      * @return {Boolean}
310      */
311     isSortable : function(col){
312         if(typeof this.config[col].sortable == "undefined"){
313             return this.defaultSortable;
314         }
315         return this.config[col].sortable;
316     },
317
318     /**
319      * Returns the rendering (formatting) function defined for the column.
320      * @param {Number} col The column index.
321      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
322      */
323     getRenderer : function(col){
324         if(!this.config[col].renderer){
325             return Roo.grid.ColumnModel.defaultRenderer;
326         }
327         return this.config[col].renderer;
328     },
329
330     /**
331      * Sets the rendering (formatting) function for a column.
332      * @param {Number} col The column index
333      * @param {Function} fn The function to use to process the cell's raw data
334      * to return HTML markup for the grid view. The render function is called with
335      * the following parameters:<ul>
336      * <li>Data value.</li>
337      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
338      * <li>css A CSS style string to apply to the table cell.</li>
339      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
340      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
341      * <li>Row index</li>
342      * <li>Column index</li>
343      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
344      */
345     setRenderer : function(col, fn){
346         this.config[col].renderer = fn;
347     },
348
349     /**
350      * Returns the width for the specified column.
351      * @param {Number} col The column index
352      * @return {Number}
353      */
354     getColumnWidth : function(col){
355         return this.config[col].width * 1 || this.defaultWidth;
356     },
357
358     /**
359      * Sets the width for a column.
360      * @param {Number} col The column index
361      * @param {Number} width The new width
362      */
363     setColumnWidth : function(col, width, suppressEvent){
364         this.config[col].width = width;
365         this.totalWidth = null;
366         if(!suppressEvent){
367              this.fireEvent("widthchange", this, col, width);
368         }
369     },
370
371     /**
372      * Returns the total width of all columns.
373      * @param {Boolean} includeHidden True to include hidden column widths
374      * @return {Number}
375      */
376     getTotalWidth : function(includeHidden){
377         if(!this.totalWidth){
378             this.totalWidth = 0;
379             for(var i = 0, len = this.config.length; i < len; i++){
380                 if(includeHidden || !this.isHidden(i)){
381                     this.totalWidth += this.getColumnWidth(i);
382                 }
383             }
384         }
385         return this.totalWidth;
386     },
387
388     /**
389      * Returns the header for the specified column.
390      * @param {Number} col The column index
391      * @return {String}
392      */
393     getColumnHeader : function(col){
394         return this.config[col].header;
395     },
396
397     /**
398      * Sets the header for a column.
399      * @param {Number} col The column index
400      * @param {String} header The new header
401      */
402     setColumnHeader : function(col, header){
403         this.config[col].header = header;
404         this.fireEvent("headerchange", this, col, header);
405     },
406
407     /**
408      * Returns the tooltip for the specified column.
409      * @param {Number} col The column index
410      * @return {String}
411      */
412     getColumnTooltip : function(col){
413             return this.config[col].tooltip;
414     },
415     /**
416      * Sets the tooltip for a column.
417      * @param {Number} col The column index
418      * @param {String} tooltip The new tooltip
419      */
420     setColumnTooltip : function(col, tooltip){
421             this.config[col].tooltip = tooltip;
422     },
423
424     /**
425      * Returns the dataIndex for the specified column.
426      * @param {Number} col The column index
427      * @return {Number}
428      */
429     getDataIndex : function(col){
430         return this.config[col].dataIndex;
431     },
432
433     /**
434      * Sets the dataIndex for a column.
435      * @param {Number} col The column index
436      * @param {Number} dataIndex The new dataIndex
437      */
438     setDataIndex : function(col, dataIndex){
439         this.config[col].dataIndex = dataIndex;
440     },
441
442     
443     
444     /**
445      * Returns true if the cell is editable.
446      * @param {Number} colIndex The column index
447      * @param {Number} rowIndex The row index - this is nto actually used..?
448      * @return {Boolean}
449      */
450     isCellEditable : function(colIndex, rowIndex){
451         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
452     },
453
454     /**
455      * Returns the editor defined for the cell/column.
456      * return false or null to disable editing.
457      * @param {Number} colIndex The column index
458      * @param {Number} rowIndex The row index
459      * @return {Object}
460      */
461     getCellEditor : function(colIndex, rowIndex){
462         return this.config[colIndex].editor;
463     },
464
465     /**
466      * Sets if a column is editable.
467      * @param {Number} col The column index
468      * @param {Boolean} editable True if the column is editable
469      */
470     setEditable : function(col, editable){
471         this.config[col].editable = editable;
472     },
473
474
475     /**
476      * Returns true if the column is hidden.
477      * @param {Number} colIndex The column index
478      * @return {Boolean}
479      */
480     isHidden : function(colIndex){
481         return this.config[colIndex].hidden;
482     },
483
484
485     /**
486      * Returns true if the column width cannot be changed
487      */
488     isFixed : function(colIndex){
489         return this.config[colIndex].fixed;
490     },
491
492     /**
493      * Returns true if the column can be resized
494      * @return {Boolean}
495      */
496     isResizable : function(colIndex){
497         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
498     },
499     /**
500      * Sets if a column is hidden.
501      * @param {Number} colIndex The column index
502      * @param {Boolean} hidden True if the column is hidden
503      */
504     setHidden : function(colIndex, hidden){
505         this.config[colIndex].hidden = hidden;
506         this.totalWidth = null;
507         this.fireEvent("hiddenchange", this, colIndex, hidden);
508     },
509
510     /**
511      * Sets the editor for a column.
512      * @param {Number} col The column index
513      * @param {Object} editor The editor object
514      */
515     setEditor : function(col, editor){
516         this.config[col].editor = editor;
517     },
518     /**
519      * Add a column (experimental...) - defaults to adding to the end..
520      * @param {Object} config 
521     */
522     addColumn : function(c)
523     {
524     
525         var i = this.config.length;
526         this.config[i] = c;
527         
528         if(typeof c.dataIndex == "undefined"){
529             c.dataIndex = i;
530         }
531         if(typeof c.renderer == "string"){
532             c.renderer = Roo.util.Format[c.renderer];
533         }
534         if(typeof c.id == "undefined"){
535             c.id = Roo.id();
536         }
537         if(c.editor && c.editor.xtype){
538             c.editor  = Roo.factory(c.editor, Roo.grid);
539         }
540         if(c.editor && c.editor.isFormField){
541             c.editor = new Roo.grid.GridEditor(c.editor);
542         }
543         this.lookup[c.id] = c;
544     }
545     
546 });
547
548 Roo.grid.ColumnModel.defaultRenderer = function(value)
549 {
550     if(typeof value == "object") {
551         return value;
552     }
553         if(typeof value == "string" && value.length < 1){
554             return "&#160;";
555         }
556     
557         return String.format("{0}", value);
558 };
559
560 // Alias for backwards compatibility
561 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;