Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / docs / source / Field3.html
1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.Field'>/**
2 </span> * @author Ed Spencer
3  * @class Ext.data.Field
4  * @extends Object
5  * 
6  * &lt;p&gt;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:&lt;/p&gt;
9  * 
10 &lt;pre&gt;&lt;code&gt;
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 &lt;/code&gt;&lt;/pre&gt;
20  * 
21  * &lt;p&gt;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:&lt;/p&gt;
24  * 
25 &lt;pre&gt;&lt;code&gt;
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 &lt;/code&gt;&lt;/pre&gt;
36  * 
37  * &lt;p&gt;&lt;u&gt;Types and conversion&lt;/u&gt;&lt;/p&gt;
38  * 
39  * &lt;p&gt;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.&lt;/p&gt;
42  * 
43  * &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
44  * do this using a {@link #convert} function. Here, we're going to create a new field based on another:&lt;/p&gt;
45  * 
46 &lt;code&gt;&lt;pre&gt;
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(&quot; &quot;),
59                     firstName = splits[0];
60
61                 return firstName;
62             }
63         }
64     ]
65 });
66 &lt;/code&gt;&lt;/pre&gt;
67  * 
68  * &lt;p&gt;Now when we create a new User, the firstName is populated automatically based on the name:&lt;/p&gt;
69  * 
70 &lt;code&gt;&lt;pre&gt;
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 &lt;/code&gt;&lt;/pre&gt;
75  * 
76  * &lt;p&gt;In fact, if we log out all of the data inside ed, we'll see this:&lt;/p&gt;
77  * 
78 &lt;code&gt;&lt;pre&gt;
79 console.log(ed.data);
80
81 //outputs this:
82 {
83     age: 0,
84     email: &quot;&quot;,
85     firstName: &quot;Ed&quot;,
86     gender: &quot;Unknown&quot;,
87     name: &quot;Ed Spencer&quot;
88 }
89 &lt;/code&gt;&lt;/pre&gt;
90  * 
91  * &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
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:&lt;/p&gt;
94  * 
95 &lt;code&gt;&lt;pre&gt;
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 &lt;/code&gt;&lt;/pre&gt;
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 <span id='Ext-data.Field-cfg-name'>    /**
139 </span>     * @cfg {String} name
140      * The name by which the field is referenced within the Model. This is referenced by, for example,
141      * the &lt;code&gt;dataIndex&lt;/code&gt; property in column definition objects passed to {@link Ext.grid.property.HeaderContainer}.
142      * &lt;p&gt;Note: In the simplest case, if no properties other than &lt;code&gt;name&lt;/code&gt; are required, a field
143      * definition may consist of just a String for the field name.&lt;/p&gt;
144      */
145     
146 <span id='Ext-data.Field-cfg-type'>    /**
147 </span>     * @cfg {Mixed} type
148      * (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;
149      * has not been specified. This may be specified as a string value. Possible values are
150      * &lt;div class=&quot;mdetail-params&quot;&gt;&lt;ul&gt;
151      * &lt;li&gt;auto (Default, implies no conversion)&lt;/li&gt;
152      * &lt;li&gt;string&lt;/li&gt;
153      * &lt;li&gt;int&lt;/li&gt;
154      * &lt;li&gt;float&lt;/li&gt;
155      * &lt;li&gt;boolean&lt;/li&gt;
156      * &lt;li&gt;date&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;
157      * &lt;p&gt;This may also be specified by referencing a member of the {@link Ext.data.Types} class.&lt;/p&gt;
158      * &lt;p&gt;Developers may create their own application-specific data types by defining new members of the
159      * {@link Ext.data.Types} class.&lt;/p&gt;
160      */
161     
162 <span id='Ext-data.Field-cfg-convert'>    /**
163 </span>     * @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:&lt;div class=&quot;mdetail-params&quot;&gt;&lt;ul&gt;
166      * &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
167      * the configured &lt;code&gt;{@link Ext.data.Field#defaultValue defaultValue}&lt;/code&gt;.&lt;/div&gt;&lt;/li&gt;
168      * &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 
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.&lt;/div&gt;&lt;/li&gt;
171      * &lt;/ul&gt;&lt;/div&gt;
172      * &lt;pre&gt;&lt;code&gt;
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      * &lt;/code&gt;&lt;/pre&gt;
220      */
221 <span id='Ext-data.Field-cfg-dateFormat'>    /**
222 </span>     * @cfg {String} dateFormat
223      * &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;
224      * &lt;p&gt;A format string for the {@link Ext.Date#parse Ext.Date.parse} function, or &quot;timestamp&quot; if the
225      * value provided by the Reader is a UNIX timestamp, or &quot;time&quot; if the value provided by the Reader is a
226      * javascript millisecond timestamp. See {@link Date}&lt;/p&gt;
227      */
228     dateFormat: null,
229     
230 <span id='Ext-data.Field-cfg-useNull'>    /**
231 </span>     * @cfg {Boolean} useNull
232      * &lt;p&gt;(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 &lt;tt&gt;false&lt;/tt&gt;
234      */
235     useNull: false,
236     
237 <span id='Ext-data.Field-cfg-defaultValue'>    /**
238 </span>     * @cfg {Mixed} defaultValue
239      * (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;
240      * when the item referenced by the &lt;code&gt;{@link Ext.data.Field#mapping mapping}&lt;/code&gt; does not exist in the data
241      * object (i.e. undefined). (defaults to &quot;&quot;)
242      */
243     defaultValue: &quot;&quot;,
244 <span id='Ext-data.Field-cfg-mapping'>    /**
245 </span>     * @cfg {String/Number} mapping
246      * &lt;p&gt;(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.&lt;/p&gt;
249      * &lt;p&gt;The form of the mapping expression depends on the Reader being used.&lt;/p&gt;
250      * &lt;div class=&quot;mdetail-params&quot;&gt;&lt;ul&gt;
251      * &lt;li&gt;{@link Ext.data.reader.Json}&lt;div class=&quot;sub-desc&quot;&gt;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.&lt;/div&gt;&lt;/li&gt;
253      * &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
254      * 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;
255      * &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
256      * of the field's value. Defaults to the field specification's Array position.&lt;/div&gt;&lt;/li&gt;
257      * &lt;/ul&gt;&lt;/div&gt;
258      * &lt;p&gt;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.&lt;/p&gt;
261      */
262     mapping: null,
263 <span id='Ext-data.Field-cfg-sortType'>    /**
264 </span>     * @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:&lt;pre&gt;&lt;code&gt;
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      * &lt;/code&gt;&lt;/pre&gt;
284      */
285     sortType : null,
286 <span id='Ext-data.Field-cfg-sortDir'>    /**
287 </span>     * @cfg {String} sortDir
288      * (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
289      * &lt;code&gt;&quot;ASC&quot;&lt;/code&gt;.
290      */
291     sortDir : &quot;ASC&quot;,
292 <span id='Ext-data.Field-cfg-allowBlank'>    /**
293 </span>     * @cfg {Boolean} allowBlank
294      * @private
295      * (Optional) Used for validating a {@link Ext.data.Model model}, defaults to &lt;code&gt;true&lt;/code&gt;.
296      * An empty value here will cause {@link Ext.data.Model}.{@link Ext.data.Model#isValid isValid}
297      * to evaluate to &lt;code&gt;false&lt;/code&gt;.
298      */
299     allowBlank : true,
300     
301 <span id='Ext-data.Field-cfg-persist'>    /**
302 </span>     * @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 &lt;tt&gt;true&lt;/tt&gt;.
307      */
308     persist: true
309 });
310 </pre></pre></body></html>