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