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