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