3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
8 * @class Ext.data.JsonWriter
9 * @extends Ext.data.DataWriter
10 * DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action.
12 Ext.data.JsonWriter = function(config) {
13 Ext.data.JsonWriter.superclass.constructor.call(this, config);
15 // careful to respect "returnJson", renamed to "encode"
16 // TODO: remove after Ext-3.0.1 release
17 if (this.returnJson != undefined) {
18 this.encode = this.returnJson;
21 Ext.extend(Ext.data.JsonWriter, Ext.data.DataWriter, {
23 * @cfg {Boolean} returnJson <b>Deprecated, will be removed in Ext-3.0.1</b>. Use {@link Ext.data.JsonWriter#encode} instead.
25 returnJson : undefined,
27 * @cfg {Boolean} encode <tt>true</tt> to {@link Ext.util.JSON#encode encode} the
28 * {@link Ext.data.DataWriter#toHash hashed data}. Defaults to <tt>true</tt>. When using
29 * {@link Ext.data.DirectProxy}, set this to <tt>false</tt> since Ext.Direct.JsonProvider will perform
30 * its own json-encoding. In addition, if you're using {@link Ext.data.HttpProxy}, setting to <tt>false</tt>
31 * will cause HttpProxy to transmit data using the <b>jsonData</b> configuration-params of {@link Ext.Ajax#request}
32 * instead of <b>params</b>. When using a {@link Ext.data.Store#restful} Store, some serverside frameworks are
33 * tuned to expect data through the jsonData mechanism. In those cases, one will want to set <b>encode: <tt>false</tt></b>, as in
34 * let the lower-level connection object (eg: Ext.Ajax) do the encoding.
39 * Final action of a write event. Apply the written data-object to params.
40 * @param {Object} http params-object to write-to.
41 * @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
42 * @param {Object/Object[]} data Data-object representing compiled Store-recordset.
44 render : function(params, baseParams, data) {
45 if (this.encode === true) {
47 Ext.apply(params, baseParams);
48 params[this.meta.root] = Ext.encode(data);
50 // defer encoding for some other layer, probably in {@link Ext.Ajax#request}. Place everything into "jsonData" key.
51 var jdata = Ext.apply({}, baseParams);
52 jdata[this.meta.root] = data;
53 params.jsonData = jdata;
57 * Implements abstract Ext.data.DataWriter#createRecord
59 * @param {Ext.data.Record} rec
62 createRecord : function(rec) {
63 return this.toHash(rec);
66 * Implements abstract Ext.data.DataWriter#updateRecord
68 * @param {Ext.data.Record} rec
71 updateRecord : function(rec) {
72 return this.toHash(rec);
76 * Implements abstract Ext.data.DataWriter#destroyRecord
78 * @param {Ext.data.Record} rec
81 destroyRecord : function(rec) {
85 * @class Ext.data.JsonReader
86 * @extends Ext.data.DataReader
87 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
88 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
90 * <p>Example code:</p>
92 var myReader = new Ext.data.JsonReader({
93 // metadata configuration options:
94 {@link #idProperty}: 'id'
95 {@link #root}: 'rows',
96 {@link #totalProperty}: 'results',
97 {@link Ext.data.DataReader#messageProperty}: "msg" // The element within the response that provides a user-feedback message (optional)
99 // the fields config option will internally create an {@link Ext.data.Record}
100 // constructor that provides mapping for reading the record data objects
101 {@link Ext.data.DataReader#fields fields}: [
102 // map Record's 'firstname' field to data object's key of same name
104 // map Record's 'job' field to data object's 'occupation' key
105 {name: 'job', mapping: 'occupation'}
109 * <p>This would consume a JSON data object of the form:</p><pre><code>
111 results: 2000, // Reader's configured {@link #totalProperty}
112 rows: [ // Reader's configured {@link #root}
113 // record data objects:
114 { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
115 { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
120 * <p><b><u>Automatic configuration using metaData</u></b></p>
121 * <p>It is possible to change a JsonReader's metadata at any time by including
122 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
123 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
124 * object using this Reader will reconfigure itself to use the newly provided
125 * field definition and fire its {@link Ext.data.Store#metachange metachange}
126 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
127 * property to perform any configuration required.</p>
128 * <p>Note that reconfiguring a Store potentially invalidates objects which may
129 * refer to Fields or Records which no longer exist.</p>
130 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
131 var myReader = new Ext.data.JsonReader();
133 * <p>The first data packet from the server would configure the reader by
134 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
135 * example, the JSON data object might take the form:</p><pre><code>
138 "{@link #idProperty}": "id",
139 "{@link #root}": "rows",
140 "{@link #totalProperty}": "results"
141 "{@link #successProperty}": "success",
142 "{@link Ext.data.DataReader#fields fields}": [
144 {"name": "job", "mapping": "occupation"}
146 // used by store to set its sortInfo
151 // {@link Ext.PagingToolbar paging data} (if applicable)
157 // Reader's configured {@link #successProperty}
159 // Reader's configured {@link #totalProperty}
161 // Reader's configured {@link #root}
162 // (this data simulates 2 results {@link Ext.PagingToolbar per page})
163 "rows": [ // <b>*Note:</b> this must be an Array
164 { "id": 1, "name": "Bill", "occupation": "Gardener" },
165 { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }
169 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
170 * <div class="mdetail-params"><ul>
171 * <li>any of the configuration options for this class</li>
172 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
173 * the JsonReader will use as an argument to the
174 * {@link Ext.data.Record#create data Record create method} in order to
175 * configure the layout of the Records it will produce.</li>
176 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
177 * which the JsonReader will use to set the {@link Ext.data.Store}'s
178 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
179 * <li>any custom properties needed</li>
183 * Create a new JsonReader
184 * @param {Object} meta Metadata configuration options.
185 * @param {Array/Object} recordType
186 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
187 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
188 * constructor created from {@link Ext.data.Record#create}.</p>
190 Ext.data.JsonReader = function(meta, recordType){
193 * @cfg {String} idProperty [id] Name of the property within a row object
194 * that contains a record identifier value. Defaults to <tt>id</tt>
197 * @cfg {String} successProperty [success] Name of the property from which to
198 * retrieve the success attribute. Defaults to <tt>success</tt>. See
199 * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
200 * for additional information.
203 * @cfg {String} totalProperty [total] Name of the property from which to
204 * retrieve the total number of records in the dataset. This is only needed
205 * if the whole dataset is not passed in one go, but is being paged from
206 * the remote server. Defaults to <tt>total</tt>.
209 * @cfg {String} root [undefined] <b>Required</b>. The name of the property
210 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
211 * An exception will be thrown if the root property is undefined. The data
212 * packet value for this property should be an empty array to clear the data
217 successProperty: 'success',
218 totalProperty: 'total'
221 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
223 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
225 * This JsonReader's metadata as passed to the constructor, or as passed in
226 * the last data packet's <b><tt>metaData</tt></b> property.
231 * This method is only used by a DataProxy which has retrieved data from a remote server.
232 * @param {Object} response The XHR object which contains the JSON data in its responseText.
233 * @return {Object} data A data block which is used by an Ext.data.Store object as
234 * a cache of Ext.data.Records.
236 read : function(response){
237 var json = response.responseText;
238 var o = Ext.decode(json);
240 throw {message: 'JsonReader.read: Json object not found'};
242 return this.readRecords(o);
246 * Decode a json response from server.
247 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
248 * @param {Object} response
249 * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
250 * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
252 readResponse : function(action, response) {
253 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
255 throw new Ext.data.JsonReader.Error('response');
258 var root = this.getRoot(o);
259 if (action === Ext.data.Api.actions.create) {
260 var def = Ext.isDefined(root);
261 if (def && Ext.isEmpty(root)) {
262 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
265 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
269 // instantiate response object
270 var res = new Ext.data.Response({
272 success: this.getSuccess(o),
273 data: (root) ? this.extractData(root, false) : [],
274 message: this.getMessage(o),
278 // blow up if no successProperty
279 if (Ext.isEmpty(res.success)) {
280 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
286 * Create a data block containing Ext.data.Records from a JSON object.
287 * @param {Object} o An object which contains an Array of row objects in the property specified
288 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
289 * which contains the total size of the dataset.
290 * @return {Object} data A data block which is used by an Ext.data.Store object as
291 * a cache of Ext.data.Records.
293 readRecords : function(o){
295 * After any data loads, the raw JSON data is available for further custom processing. If no data is
296 * loaded or there is a load exception this property will be undefined.
301 this.onMetaChange(o.metaData);
303 var s = this.meta, Record = this.recordType,
304 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
306 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
308 v = parseInt(this.getTotal(o), 10);
313 if(s.successProperty){
314 v = this.getSuccess(o);
315 if(v === false || v === 'false'){
320 // TODO return Ext.data.Response instance instead. @see #readResponse
323 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
324 totalRecords : totalRecords
329 buildExtractors : function() {
333 var s = this.meta, Record = this.recordType,
334 f = Record.prototype.fields, fi = f.items, fl = f.length;
336 if(s.totalProperty) {
337 this.getTotal = this.createAccessor(s.totalProperty);
339 if(s.successProperty) {
340 this.getSuccess = this.createAccessor(s.successProperty);
342 if (s.messageProperty) {
343 this.getMessage = this.createAccessor(s.messageProperty);
345 this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
346 if (s.id || s.idProperty) {
347 var g = this.createAccessor(s.id || s.idProperty);
348 this.getId = function(rec) {
350 return (r === undefined || r === '') ? null : r;
353 this.getId = function(){return null;};
356 for(var i = 0; i < fl; i++){
358 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
359 ef.push(this.createAccessor(map));
366 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
368 simpleAccess : function(obj, subsc) {
375 createAccessor : function(){
377 return function(expr) {
379 return(re.test(expr)) ?
380 new Function('obj', 'return obj.' + expr) :
390 * type-casts a single row of raw-data from server
391 * @param {Object} data
392 * @param {Array} items
393 * @param {Integer} len
396 extractValues : function(data, items, len) {
398 for(var j = 0; j < len; j++){
400 var v = this.ef[j](data);
401 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
408 * @class Ext.data.JsonReader.Error
409 * Error class for JsonReader
411 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
412 constructor : function(message, arg) {
414 Ext.Error.call(this, message);
416 name : 'Ext.data.JsonReader'
418 Ext.apply(Ext.data.JsonReader.Error.prototype, {
420 'response': 'An error occurred while json-decoding your server response',
421 'successProperty-response': 'Could not locate your "successProperty" in your server response. Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response. See the JsonReader docs.',
422 'root-undefined-config': 'Your JsonReader was configured without a "root" property. Please review your JsonReader config and make sure to define the root property. See the JsonReader docs.',
423 'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty" Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id"). See the JsonReader docs.',
424 'root-empty': 'Data was expected to be returned by the server in the "root" property of the response. Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response. See JsonReader docs.'
428 * @class Ext.data.ArrayReader
429 * @extends Ext.data.JsonReader
430 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an Array.
431 * Each element of that Array represents a row of data fields. The
432 * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
433 * of the field definition if it exists, or the field's ordinal position in the definition.</p>
434 * <p>Example code:</p>
436 var Employee = Ext.data.Record.create([
437 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
438 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
440 var myReader = new Ext.data.ArrayReader({
444 * <p>This would consume an Array like this:</p>
446 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
449 * Create a new ArrayReader
450 * @param {Object} meta Metadata configuration options.
451 * @param {Array/Object} recordType
452 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
453 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
454 * constructor created from {@link Ext.data.Record#create}.</p>
456 Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
458 * @cfg {String} successProperty
462 * @cfg {Number} id (optional) The subscript within row Array that provides an ID for the Record.
463 * Deprecated. Use {@link #idIndex} instead.
466 * @cfg {Number} idIndex (optional) The subscript within row Array that provides an ID for the Record.
469 * Create a data block containing Ext.data.Records from an Array.
470 * @param {Object} o An Array of row objects which represents the dataset.
471 * @return {Object} data A data block which is used by an Ext.data.Store object as
472 * a cache of Ext.data.Records.
474 readRecords : function(o){
477 sid = s ? Ext.num(s.idIndex, s.id) : null,
478 recordType = this.recordType,
479 fields = recordType.prototype.fields,
483 var root = this.getRoot(o);
485 for(var i = 0, len = root.length; i < len; i++) {
488 id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
489 for(var j = 0, jlen = fields.length; j < jlen; j++) {
490 var f = fields.items[j],
491 k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
492 v = n[k] !== undefined ? n[k] : f.defaultValue;
496 var record = new recordType(values, id);
498 records[records.length] = record;
501 var totalRecords = records.length;
503 if(s.totalProperty) {
504 v = parseInt(this.getTotal(o), 10);
512 totalRecords : totalRecords
516 * @class Ext.data.ArrayStore
517 * @extends Ext.data.Store
518 * <p>Formerly known as "SimpleStore".</p>
519 * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
520 * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p>
521 * <p>A store configuration would be something like:<pre><code>
522 var store = new Ext.data.ArrayStore({
530 {name: 'price', type: 'float'},
531 {name: 'change', type: 'float'},
532 {name: 'pctChange', type: 'float'},
533 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
537 * <p>This store is configured to consume a returned object of the form:<pre><code>
539 ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
540 ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
541 ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
542 ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
543 ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
546 * An object literal of this form could also be used as the {@link #data} config option.</p>
547 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
548 * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p>
550 * @param {Object} config
553 Ext.data.ArrayStore = Ext.extend(Ext.data.Store, {
555 * @cfg {Ext.data.DataReader} reader @hide
557 constructor: function(config){
558 Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
559 reader: new Ext.data.ArrayReader(config)
563 loadData : function(data, append){
564 if(this.expandData === true){
566 for(var i = 0, len = data.length; i < len; i++){
567 r[r.length] = [data[i]];
571 Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
574 Ext.reg('arraystore', Ext.data.ArrayStore);
577 Ext.data.SimpleStore = Ext.data.ArrayStore;
578 Ext.reg('simplestore', Ext.data.SimpleStore);/**
579 * @class Ext.data.JsonStore
580 * @extends Ext.data.Store
581 * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
582 * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
583 * <p>A store configuration would be something like:<pre><code>
584 var store = new Ext.data.JsonStore({
587 url: 'get-images.php',
592 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
595 * <p>This store is configured to consume a returned object of the form:<pre><code>
598 {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
599 {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
603 * An object literal of this form could also be used as the {@link #data} config option.</p>
604 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
605 * <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
607 * @param {Object} config
610 Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
612 * @cfg {Ext.data.DataReader} reader @hide
614 constructor: function(config){
615 Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
616 reader: new Ext.data.JsonReader(config)
620 Ext.reg('jsonstore', Ext.data.JsonStore);