Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / data / DataField.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.data.Field
9  * <p>This class encapsulates the field definition information specified in the field definition objects
10  * passed to {@link Ext.data.Record#create}.</p>
11  * <p>Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
12  * and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
13  */
14 Ext.data.Field = function(config){
15     if(typeof config == "string"){
16         config = {name: config};
17     }
18     Ext.apply(this, config);
19
20     if(!this.type){
21         this.type = "auto";
22     }
23
24     var st = Ext.data.SortTypes;
25     // named sortTypes are supported, here we look them up
26     if(typeof this.sortType == "string"){
27         this.sortType = st[this.sortType];
28     }
29
30     // set default sortType for strings and dates
31     if(!this.sortType){
32         switch(this.type){
33             case "string":
34                 this.sortType = st.asUCString;
35                 break;
36             case "date":
37                 this.sortType = st.asDate;
38                 break;
39             default:
40                 this.sortType = st.none;
41         }
42     }
43
44     // define once
45     var stripRe = /[\$,%]/g;
46
47     // prebuilt conversion function for this field, instead of
48     // switching every time we're reading a value
49     if(!this.convert){
50         var cv, dateFormat = this.dateFormat;
51         switch(this.type){
52             case "":
53             case "auto":
54             case undefined:
55                 cv = function(v){ return v; };
56                 break;
57             case "string":
58                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
59                 break;
60             case "int":
61                 cv = function(v){
62                     return v !== undefined && v !== null && v !== '' ?
63                            parseInt(String(v).replace(stripRe, ""), 10) : '';
64                     };
65                 break;
66             case "float":
67                 cv = function(v){
68                     return v !== undefined && v !== null && v !== '' ?
69                            parseFloat(String(v).replace(stripRe, ""), 10) : '';
70                     };
71                 break;
72             case "bool":
73             case "boolean":
74                 cv = function(v){ return v === true || v === "true" || v == 1; };
75                 break;
76             case "date":
77                 cv = function(v){
78                     if(!v){
79                         return '';
80                     }
81                     if(Ext.isDate(v)){
82                         return v;
83                     }
84                     if(dateFormat){
85                         if(dateFormat == "timestamp"){
86                             return new Date(v*1000);
87                         }
88                         if(dateFormat == "time"){
89                             return new Date(parseInt(v, 10));
90                         }
91                         return Date.parseDate(v, dateFormat);
92                     }
93                     var parsed = Date.parse(v);
94                     return parsed ? new Date(parsed) : null;
95                 };
96              break;
97
98         }
99         this.convert = cv;
100     }
101 };
102
103 Ext.data.Field.prototype = {
104     /**
105      * @cfg {String} name
106      * The name by which the field is referenced within the Record. This is referenced by, for example,
107      * the <tt>dataIndex</tt> property in column definition objects passed to {@link Ext.grid.ColumnModel}.
108      * <p>Note: In the simplest case, if no properties other than <tt>name</tt> are required, a field
109      * definition may consist of just a String for the field name.</p>
110      */
111     /**
112      * @cfg {String} type
113      * (Optional) The data type for conversion to displayable value if <tt>{@link Ext.data.Field#convert convert}</tt>
114      * has not been specified. Possible values are
115      * <div class="mdetail-params"><ul>
116      * <li>auto (Default, implies no conversion)</li>
117      * <li>string</li>
118      * <li>int</li>
119      * <li>float</li>
120      * <li>boolean</li>
121      * <li>date</li></ul></div>
122      */
123     /**
124      * @cfg {Function} convert
125      * (Optional) A function which converts the value provided by the Reader into an object that will be stored
126      * in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
127      * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
128      * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
129      * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
130      * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
131      *  ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
132      * </ul></div>
133      * <pre><code>
134 // example of convert function
135 function fullName(v, record){
136     return record.name.last + ', ' + record.name.first;
137 }
138
139 function location(v, record){
140     return !record.city ? '' : (record.city + ', ' + record.state);
141 }
142
143 var Dude = Ext.data.Record.create([
144     {name: 'fullname',  convert: fullName},
145     {name: 'firstname', mapping: 'name.first'},
146     {name: 'lastname',  mapping: 'name.last'},
147     {name: 'city', defaultValue: 'homeless'},
148     'state',
149     {name: 'location',  convert: location}
150 ]);
151
152 // create the data store
153 var store = new Ext.data.Store({
154     reader: new Ext.data.JsonReader(
155         {
156             idProperty: 'key',
157             root: 'daRoot',  
158             totalProperty: 'total'
159         },
160         Dude  // recordType
161     )
162 });
163
164 var myData = [
165     { key: 1,
166       name: { first: 'Fat',    last:  'Albert' }
167       // notice no city, state provided in data object
168     },
169     { key: 2,
170       name: { first: 'Barney', last:  'Rubble' },
171       city: 'Bedrock', state: 'Stoneridge'
172     },
173     { key: 3,
174       name: { first: 'Cliff',  last:  'Claven' },
175       city: 'Boston',  state: 'MA'
176     }
177 ];
178      * </code></pre>
179      */
180     /**
181      * @cfg {String} dateFormat
182      * (Optional) A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
183      * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
184      * javascript millisecond timestamp.
185      */
186     dateFormat: null,
187     /**
188      * @cfg {Mixed} defaultValue
189      * (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b>
190      * when the item referenced by the <tt>{@link Ext.data.Field#mapping mapping}</tt> does not exist in the data
191      * object (i.e. undefined). (defaults to "")
192      */
193     defaultValue: "",
194     /**
195      * @cfg {String/Number} mapping
196      * <p>(Optional) A path expression for use by the {@link Ext.data.DataReader} implementation
197      * that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object.
198      * If the path expression is the same as the field name, the mapping may be omitted.</p>
199      * <p>The form of the mapping expression depends on the Reader being used.</p>
200      * <div class="mdetail-params"><ul>
201      * <li>{@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript
202      * expression to reference the data from an element of the data item's {@link Ext.data.JsonReader#root root} Array. Defaults to the field name.</div></li>
203      * <li>{@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
204      * item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li>
205      * <li>{@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index
206      * of the field's value. Defaults to the field specification's Array position.</div></li>
207      * </ul></div>
208      * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
209      * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
210      * return the desired data.</p>
211      */
212     mapping: null,
213     /**
214      * @cfg {Function} sortType
215      * (Optional) A function which converts a Field's value to a comparable value in order to ensure
216      * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
217      * sort example:<pre><code>
218 // current sort     after sort we want
219 // +-+------+          +-+------+
220 // |1|First |          |1|First |
221 // |2|Last  |          |3|Second|
222 // |3|Second|          |2|Last  |
223 // +-+------+          +-+------+
224
225 sortType: function(value) {
226    switch (value.toLowerCase()) // native toLowerCase():
227    {
228       case 'first': return 1;
229       case 'second': return 2;
230       default: return 3;
231    }
232 }
233      * </code></pre>
234      */
235     sortType : null,
236     /**
237      * @cfg {String} sortDir
238      * (Optional) Initial direction to sort (<tt>"ASC"</tt> or  <tt>"DESC"</tt>).  Defaults to
239      * <tt>"ASC"</tt>.
240      */
241     sortDir : "ASC",
242         /**
243          * @cfg {Boolean} allowBlank 
244          * (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <tt>true</tt>.
245          * An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}
246          * to evaluate to <tt>false</tt>.
247          */
248         allowBlank : true
249 };