Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / data / Field.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  * @author Ed Spencer
17  * @class Ext.data.Field
18  * @extends Object
19  * 
20  * <p>Fields are used to define what a Model is. They aren't instantiated directly - instead, when we create a class 
21  * that extends {@link Ext.data.Model}, it will automatically create a Field instance for each field configured in a 
22  * {@link Ext.data.Model Model}. For example, we might set up a model like this:</p>
23  * 
24 <pre><code>
25 Ext.define('User', {
26     extend: 'Ext.data.Model',
27     fields: [
28         'name', 'email',
29         {name: 'age', type: 'int'},
30         {name: 'gender', type: 'string', defaultValue: 'Unknown'}
31     ]
32 });
33 </code></pre>
34  * 
35  * <p>Four fields will have been created for the User Model - name, email, age and gender. Note that we specified a
36  * couple of different formats here; if we only pass in the string name of the field (as with name and email), the
37  * field is set up with the 'auto' type. It's as if we'd done this instead:</p>
38  * 
39 <pre><code>
40 Ext.define('User', {
41     extend: 'Ext.data.Model',
42     fields: [
43         {name: 'name', type: 'auto'},
44         {name: 'email', type: 'auto'},
45         {name: 'age', type: 'int'},
46         {name: 'gender', type: 'string', defaultValue: 'Unknown'}
47     ]
48 });
49 </code></pre>
50  * 
51  * <p><u>Types and conversion</u></p>
52  * 
53  * <p>The {@link #type} is important - it's used to automatically convert data passed to the field into the correct
54  * format. In our example above, the name and email fields used the 'auto' type and will just accept anything that is
55  * passed into them. The 'age' field had an 'int' type however, so if we passed 25.4 this would be rounded to 25.</p>
56  * 
57  * <p>Sometimes a simple type isn't enough, or we want to perform some processing when we load a Field's data. We can
58  * do this using a {@link #convert} function. Here, we're going to create a new field based on another:</p>
59  * 
60 <code><pre>
61 Ext.define('User', {
62     extend: 'Ext.data.Model',
63     fields: [
64         'name', 'email',
65         {name: 'age', type: 'int'},
66         {name: 'gender', type: 'string', defaultValue: 'Unknown'},
67
68         {
69             name: 'firstName',
70             convert: function(value, record) {
71                 var fullName  = record.get('name'),
72                     splits    = fullName.split(" "),
73                     firstName = splits[0];
74
75                 return firstName;
76             }
77         }
78     ]
79 });
80 </code></pre>
81  * 
82  * <p>Now when we create a new User, the firstName is populated automatically based on the name:</p>
83  * 
84 <code><pre>
85 var ed = Ext.ModelManager.create({name: 'Ed Spencer'}, 'User');
86
87 console.log(ed.get('firstName')); //logs 'Ed', based on our convert function
88 </code></pre>
89  * 
90  * <p>In fact, if we log out all of the data inside ed, we'll see this:</p>
91  * 
92 <code><pre>
93 console.log(ed.data);
94
95 //outputs this:
96 {
97     age: 0,
98     email: "",
99     firstName: "Ed",
100     gender: "Unknown",
101     name: "Ed Spencer"
102 }
103 </code></pre>
104  * 
105  * <p>The age field has been given a default of zero because we made it an int type. As an auto field, email has
106  * defaulted to an empty string. When we registered the User model we set gender's {@link #defaultValue} to 'Unknown'
107  * so we see that now. Let's correct that and satisfy ourselves that the types work as we expect:</p>
108  * 
109 <code><pre>
110 ed.set('gender', 'Male');
111 ed.get('gender'); //returns 'Male'
112
113 ed.set('age', 25.4);
114 ed.get('age'); //returns 25 - we wanted an int, not a float, so no decimal places allowed
115 </code></pre>
116  * 
117  */
118 Ext.define('Ext.data.Field', {
119     requires: ['Ext.data.Types', 'Ext.data.SortTypes'],
120     alias: 'data.field',
121     
122     constructor : function(config) {
123         if (Ext.isString(config)) {
124             config = {name: config};
125         }
126         Ext.apply(this, config);
127         
128         var types = Ext.data.Types,
129             st = this.sortType,
130             t;
131
132         if (this.type) {
133             if (Ext.isString(this.type)) {
134                 this.type = types[this.type.toUpperCase()] || types.AUTO;
135             }
136         } else {
137             this.type = types.AUTO;
138         }
139
140         // named sortTypes are supported, here we look them up
141         if (Ext.isString(st)) {
142             this.sortType = Ext.data.SortTypes[st];
143         } else if(Ext.isEmpty(st)) {
144             this.sortType = this.type.sortType;
145         }
146
147         if (!this.convert) {
148             this.convert = this.type.convert;
149         }
150     },
151     
152     /**
153      * @cfg {String} name
154      * The name by which the field is referenced within the Model. This is referenced by, for example,
155      * the <code>dataIndex</code> property in column definition objects passed to {@link Ext.grid.property.HeaderContainer}.
156      * <p>Note: In the simplest case, if no properties other than <code>name</code> are required, a field
157      * definition may consist of just a String for the field name.</p>
158      */
159     
160     /**
161      * @cfg {Mixed} type
162      * (Optional) The data type for automatic conversion from received data to the <i>stored</i> value if <code>{@link Ext.data.Field#convert convert}</code>
163      * has not been specified. This may be specified as a string value. Possible values are
164      * <div class="mdetail-params"><ul>
165      * <li>auto (Default, implies no conversion)</li>
166      * <li>string</li>
167      * <li>int</li>
168      * <li>float</li>
169      * <li>boolean</li>
170      * <li>date</li></ul></div>
171      * <p>This may also be specified by referencing a member of the {@link Ext.data.Types} class.</p>
172      * <p>Developers may create their own application-specific data types by defining new members of the
173      * {@link Ext.data.Types} class.</p>
174      */
175     
176     /**
177      * @cfg {Function} convert
178      * (Optional) A function which converts the value provided by the Reader into an object that will be stored
179      * in the Model. It is passed the following parameters:<div class="mdetail-params"><ul>
180      * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
181      * the configured <code>{@link Ext.data.Field#defaultValue defaultValue}</code>.</div></li>
182      * <li><b>rec</b> : Ext.data.Model<div class="sub-desc">The data object containing the Model as read so far by the 
183      * Reader. Note that the Model may not be fully populated at this point as the fields are read in the order that 
184      * they are defined in your {@link #fields} array.</div></li>
185      * </ul></div>
186      * <pre><code>
187 // example of convert function
188 function fullName(v, record){
189     return record.name.last + ', ' + record.name.first;
190 }
191
192 function location(v, record){
193     return !record.city ? '' : (record.city + ', ' + record.state);
194 }
195
196 Ext.define('Dude', {
197     extend: 'Ext.data.Model',
198     fields: [
199         {name: 'fullname',  convert: fullName},
200         {name: 'firstname', mapping: 'name.first'},
201         {name: 'lastname',  mapping: 'name.last'},
202         {name: 'city', defaultValue: 'homeless'},
203         'state',
204         {name: 'location',  convert: location}
205     ]
206 });
207
208 // create the data store
209 var store = new Ext.data.Store({
210     reader: {
211         type: 'json',
212         model: 'Dude',
213         idProperty: 'key',
214         root: 'daRoot',
215         totalProperty: 'total'
216     }
217 });
218
219 var myData = [
220     { key: 1,
221       name: { first: 'Fat',    last:  'Albert' }
222       // notice no city, state provided in data object
223     },
224     { key: 2,
225       name: { first: 'Barney', last:  'Rubble' },
226       city: 'Bedrock', state: 'Stoneridge'
227     },
228     { key: 3,
229       name: { first: 'Cliff',  last:  'Claven' },
230       city: 'Boston',  state: 'MA'
231     }
232 ];
233      * </code></pre>
234      */
235     /**
236      * @cfg {String} dateFormat
237      * <p>(Optional) Used when converting received data into a Date when the {@link #type} is specified as <code>"date"</code>.</p>
238      * <p>A format string for the {@link Ext.Date#parse Ext.Date.parse} function, or "timestamp" if the
239      * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
240      * javascript millisecond timestamp. See {@link Ext.Date}</p>
241      */
242     dateFormat: null,
243     
244     /**
245      * @cfg {Boolean} useNull
246      * <p>(Optional) Use when converting received data into a Number type (either int or float). If the value cannot be parsed,
247      * null will be used if useNull is true, otherwise the value will be 0. Defaults to <tt>false</tt>
248      */
249     useNull: false,
250     
251     /**
252      * @cfg {Mixed} defaultValue
253      * (Optional) The default value used <b>when a Model is being created by a {@link Ext.data.reader.Reader Reader}</b>
254      * when the item referenced by the <code>{@link Ext.data.Field#mapping mapping}</code> does not exist in the data
255      * object (i.e. undefined). (defaults to "")
256      */
257     defaultValue: "",
258     /**
259      * @cfg {String/Number} mapping
260      * <p>(Optional) A path expression for use by the {@link Ext.data.reader.Reader} implementation
261      * that is creating the {@link Ext.data.Model Model} to extract the Field value from the data object.
262      * If the path expression is the same as the field name, the mapping may be omitted.</p>
263      * <p>The form of the mapping expression depends on the Reader being used.</p>
264      * <div class="mdetail-params"><ul>
265      * <li>{@link Ext.data.reader.Json}<div class="sub-desc">The mapping is a string containing the javascript
266      * expression to reference the data from an element of the data item's {@link Ext.data.reader.Json#root root} Array. Defaults to the field name.</div></li>
267      * <li>{@link Ext.data.reader.Xml}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
268      * item relative to the DOM element that represents the {@link Ext.data.reader.Xml#record record}. Defaults to the field name.</div></li>
269      * <li>{@link Ext.data.reader.Array}<div class="sub-desc">The mapping is a number indicating the Array index
270      * of the field's value. Defaults to the field specification's Array position.</div></li>
271      * </ul></div>
272      * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
273      * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
274      * return the desired data.</p>
275      */
276     mapping: null,
277     /**
278      * @cfg {Function} sortType
279      * (Optional) A function which converts a Field's value to a comparable value in order to ensure
280      * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
281      * sort example:<pre><code>
282 // current sort     after sort we want
283 // +-+------+          +-+------+
284 // |1|First |          |1|First |
285 // |2|Last  |          |3|Second|
286 // |3|Second|          |2|Last  |
287 // +-+------+          +-+------+
288
289 sortType: function(value) {
290    switch (value.toLowerCase()) // native toLowerCase():
291    {
292       case 'first': return 1;
293       case 'second': return 2;
294       default: return 3;
295    }
296 }
297      * </code></pre>
298      */
299     sortType : null,
300     /**
301      * @cfg {String} sortDir
302      * (Optional) Initial direction to sort (<code>"ASC"</code> or  <code>"DESC"</code>).  Defaults to
303      * <code>"ASC"</code>.
304      */
305     sortDir : "ASC",
306     /**
307      * @cfg {Boolean} allowBlank
308      * @private
309      * (Optional) Used for validating a {@link Ext.data.Model model}, defaults to <code>true</code>.
310      * An empty value here will cause {@link Ext.data.Model}.{@link Ext.data.Model#isValid isValid}
311      * to evaluate to <code>false</code>.
312      */
313     allowBlank : true,
314     
315     /**
316      * @cfg {Boolean} persist
317      * False to exclude this field from the {@link Ext.data.Model#modified} fields in a model. This 
318      * will also exclude the field from being written using a {@link Ext.data.writer.Writer}. This option
319      * is useful when model fields are used to keep state on the client but do not need to be persisted
320      * to the server. Defaults to <tt>true</tt>.
321      */
322     persist: true
323 });
324