Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / grid / property / Grid.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.grid.property.Grid
17  * @extends Ext.grid.Panel
18  * A specialized grid implementation intended to mimic the traditional property grid as typically seen in
19  * development IDEs.  Each row in the grid represents a property of some object, and the data is stored
20  * as a set of name/value pairs in {@link Ext.grid.property.Property Properties}.  Example usage:
21  * <pre><code>
22 var grid = new Ext.grid.property.Grid({
23     title: 'Properties Grid',
24     width: 300,
25     renderTo: 'grid-ct',
26     source: {
27         "(name)": "My Object",
28         "Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),
29         "Available": false,
30         "Version": .01,
31         "Description": "A test object"
32     }
33 });
34 </code></pre>
35  */
36 Ext.define('Ext.grid.property.Grid', {
37
38     extend: 'Ext.grid.Panel',
39
40     alias: 'widget.propertygrid',
41
42     alternateClassName: 'Ext.grid.PropertyGrid',
43
44     uses: [
45        'Ext.grid.plugin.CellEditing',
46        'Ext.grid.property.Store',
47        'Ext.grid.property.HeaderContainer',
48        'Ext.XTemplate',
49        'Ext.grid.CellEditor',
50        'Ext.form.field.Date',
51        'Ext.form.field.Text',
52        'Ext.form.field.Number'
53     ],
54
55    /**
56     * @cfg {Object} propertyNames An object containing custom property name/display name pairs.
57     * If specified, the display name will be shown in the name column instead of the property name.
58     */
59
60     /**
61     * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details).
62     */
63
64     /**
65     * @cfg {Object} customEditors An object containing name/value pairs of custom editor type definitions that allow
66     * the grid to support additional types of editable fields.  By default, the grid supports strongly-typed editing
67     * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
68     * associated with a custom input control by specifying a custom editor.  The name of the editor
69     * type should correspond with the name of the property that will use the editor.  Example usage:
70     * <pre><code>
71 var grid = new Ext.grid.property.Grid({
72
73     // Custom editors for certain property names
74     customEditors: {
75         evtStart: Ext.create('Ext.form.TimeField' {selectOnFocus:true})
76     },
77
78     // Displayed name for property names in the source
79     propertyNames: {
80         evtStart: 'Start Time'
81     },
82
83     // Data object containing properties to edit
84     source: {
85         evtStart: '10:00 AM'
86     }
87 });
88 </code></pre>
89     */
90
91     /**
92     * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details).
93     */
94
95     /**
96     * @cfg {Object} customRenderers An object containing name/value pairs of custom renderer type definitions that allow
97     * the grid to support custom rendering of fields.  By default, the grid supports strongly-typed rendering
98     * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
99     * associated with the type of the value.  The name of the renderer type should correspond with the name of the property
100     * that it will render.  Example usage:
101     * <pre><code>
102 var grid = Ext.create('Ext.grid.property.Grid', {
103     customRenderers: {
104         Available: function(v){
105             if (v) {
106                 return '<span style="color: green;">Yes</span>';
107             } else {
108                 return '<span style="color: red;">No</span>';
109             }
110         }
111     },
112     source: {
113         Available: true
114     }
115 });
116 </code></pre>
117     */
118
119     /**
120      * @cfg {String} valueField
121      * Optional. The name of the field from the property store to use as the value field name. Defaults to <code>'value'</code>
122      * This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
123      */
124     valueField: 'value',
125
126     /**
127      * @cfg {String} nameField
128      * Optional. The name of the field from the property store to use as the property field name. Defaults to <code>'name'</code>
129      * This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
130      */
131     nameField: 'name',
132
133     /**
134      * @cfg {Number} nameColumnWidth
135      * Optional. Specify the width for the name column. The value column will take any remaining space. Defaults to <tt>115</tt>.
136      */
137
138     // private config overrides
139     enableColumnMove: false,
140     columnLines: true,
141     stripeRows: false,
142     trackMouseOver: false,
143     clicksToEdit: 1,
144     enableHdMenu: false,
145
146     // private
147     initComponent : function(){
148         var me = this;
149
150         me.addCls(Ext.baseCSSPrefix + 'property-grid');
151         me.plugins = me.plugins || [];
152
153         // Enable cell editing. Inject a custom startEdit which always edits column 1 regardless of which column was clicked.
154         me.plugins.push(Ext.create('Ext.grid.plugin.CellEditing', {
155             clicksToEdit: me.clicksToEdit,
156
157             // Inject a startEdit which always edits the value column
158             startEdit: function(record, column) {
159                 // Maintainer: Do not change this 'this' to 'me'! It is the CellEditing object's own scope.
160                 return this.self.prototype.startEdit.call(this, record, me.headerCt.child('#' + me.valueField));
161             }
162         }));
163
164         me.selModel = {
165             selType: 'cellmodel',
166             onCellSelect: function(position) {
167                 if (position.column != 1) {
168                     position.column = 1;
169                 }
170                 return this.self.prototype.onCellSelect.call(this, position);
171             }
172         };
173         me.customRenderers = me.customRenderers || {};
174         me.customEditors = me.customEditors || {};
175
176         // Create a property.Store from the source object unless configured with a store
177         if (!me.store) {
178             me.propStore = me.store = Ext.create('Ext.grid.property.Store', me, me.source);
179         }
180
181         me.store.sort('name', 'ASC');
182         me.columns = Ext.create('Ext.grid.property.HeaderContainer', me, me.store);
183
184         me.addEvents(
185             /**
186              * @event beforepropertychange
187              * Fires before a property value changes.  Handlers can return false to cancel the property change
188              * (this will internally call {@link Ext.data.Model#reject} on the property's record).
189              * @param {Object} source The source data object for the grid (corresponds to the same object passed in
190              * as the {@link #source} config property).
191              * @param {String} recordId The record's id in the data store
192              * @param {Mixed} value The current edited property value
193              * @param {Mixed} oldValue The original property value prior to editing
194              */
195             'beforepropertychange',
196             /**
197              * @event propertychange
198              * Fires after a property value has changed.
199              * @param {Object} source The source data object for the grid (corresponds to the same object passed in
200              * as the {@link #source} config property).
201              * @param {String} recordId The record's id in the data store
202              * @param {Mixed} value The current edited property value
203              * @param {Mixed} oldValue The original property value prior to editing
204              */
205             'propertychange'
206         );
207         me.callParent();
208
209         // Inject a custom implementation of walkCells which only goes up or down
210         me.getView().walkCells = this.walkCells;
211
212         // Set up our default editor set for the 4 atomic data types
213         me.editors = {
214             'date'    : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.Date',   {selectOnFocus: true})}),
215             'string'  : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.Text',   {selectOnFocus: true})}),
216             'number'  : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.Number', {selectOnFocus: true})}),
217             'boolean' : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.ComboBox', {
218                 editable: false,
219                 store: [[ true, me.headerCt.trueText ], [false, me.headerCt.falseText ]]
220             })})
221         };
222
223         // Track changes to the data so we can fire our events.
224         me.store.on('update', me.onUpdate, me);
225     },
226
227     // private
228     onUpdate : function(store, record, operation) {
229         var me = this,
230             v, oldValue;
231
232         if (operation == Ext.data.Model.EDIT) {
233             v = record.get(me.valueField);
234             oldValue = record.modified.value;
235             if (me.fireEvent('beforepropertychange', me.source, record.getId(), v, oldValue) !== false) {
236                 if (me.source) {
237                     me.source[record.getId()] = v;
238                 }
239                 record.commit();
240                 me.fireEvent('propertychange', me.source, record.getId(), v, oldValue);
241             } else {
242                 record.reject();
243             }
244         }
245     },
246
247     // Custom implementation of walkCells which only goes up and down.
248     walkCells: function(pos, direction, e, preventWrap, verifierFn, scope) {
249         if (direction == 'left') {
250             direction = 'up';
251         } else if (direction == 'right') {
252             direction = 'down';
253         }
254         pos = Ext.view.Table.prototype.walkCells.call(this, pos, direction, e, preventWrap, verifierFn, scope);
255         if (!pos.column) {
256             pos.column = 1;
257         }
258         return pos;
259     },
260
261     // private
262     // returns the correct editor type for the property type, or a custom one keyed by the property name
263     getCellEditor : function(record, column) {
264         var me = this,
265             propName = record.get(me.nameField),
266             val = record.get(me.valueField),
267             editor = me.customEditors[propName];
268
269         // A custom editor was found. If not already wrapped with a CellEditor, wrap it, and stash it back
270         // If it's not even a Field, just a config object, instantiate it before wrapping it.
271         if (editor) {
272             if (!(editor instanceof Ext.grid.CellEditor)) {
273                 if (!(editor instanceof Ext.form.field.Base)) {
274                     editor = Ext.ComponentManager.create(editor, 'textfield');
275                 }
276                 editor = me.customEditors[propName] = Ext.create('Ext.grid.CellEditor', { field: editor });
277             }
278         } else if (Ext.isDate(val)) {
279             editor = me.editors.date;
280         } else if (Ext.isNumber(val)) {
281             editor = me.editors.number;
282         } else if (Ext.isBoolean(val)) {
283             editor = me.editors['boolean'];
284         } else {
285             editor = me.editors.string;
286         }
287
288         // Give the editor a unique ID because the CellEditing plugin caches them
289         editor.editorId = propName;
290         return editor;
291     },
292
293     beforeDestroy: function() {
294         var me = this;
295         me.callParent();
296         me.destroyEditors(me.editors);
297         me.destroyEditors(me.customEditors);
298         delete me.source;
299     },
300
301     destroyEditors: function (editors) {
302         for (var ed in editors) {
303             if (editors.hasOwnProperty(ed)) {
304                 Ext.destroy(editors[ed]);
305             }
306         }
307     },
308
309     /**
310      * Sets the source data object containing the property data.  The data object can contain one or more name/value
311      * pairs representing all of the properties of an object to display in the grid, and this data will automatically
312      * be loaded into the grid's {@link #store}.  The values should be supplied in the proper data type if needed,
313      * otherwise string type will be assumed.  If the grid already contains data, this method will replace any
314      * existing data.  See also the {@link #source} config value.  Example usage:
315      * <pre><code>
316 grid.setSource({
317     "(name)": "My Object",
318     "Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),  // date type
319     "Available": false,  // boolean type
320     "Version": .01,      // decimal type
321     "Description": "A test object"
322 });
323 </code></pre>
324      * @param {Object} source The data object
325      */
326     setSource: function(source) {
327         this.source = source;
328         this.propStore.setSource(source);
329     },
330
331     /**
332      * Gets the source data object containing the property data.  See {@link #setSource} for details regarding the
333      * format of the data object.
334      * @return {Object} The data object
335      */
336     getSource: function() {
337         return this.propStore.getSource();
338     },
339
340     /**
341      * Sets the value of a property.
342      * @param {String} prop The name of the property to set
343      * @param {Mixed} value The value to test
344      * @param {Boolean} create (Optional) True to create the property if it doesn't already exist. Defaults to <tt>false</tt>.
345      */
346     setProperty: function(prop, value, create) {
347         this.propStore.setValue(prop, value, create);
348     },
349
350     /**
351      * Removes a property from the grid.
352      * @param {String} prop The name of the property to remove
353      */
354     removeProperty: function(prop) {
355         this.propStore.remove(prop);
356     }
357
358     /**
359      * @cfg store
360      * @hide
361      */
362     /**
363      * @cfg colModel
364      * @hide
365      */
366     /**
367      * @cfg cm
368      * @hide
369      */
370     /**
371      * @cfg columns
372      * @hide
373      */
374 });