3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.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 = Ext.extend(Ext.data.DataWriter, {
14 * @cfg {Boolean} encode <p><tt>true</tt> to {@link Ext.util.JSON#encode JSON encode} the
15 * {@link Ext.data.DataWriter#toHash hashed data} into a standard HTTP parameter named after this
16 * Reader's <code>meta.root</code> property which, by default is imported from the associated Reader. Defaults to <tt>true</tt>.</p>
17 * <p>If set to <code>false</code>, the hashed data is {@link Ext.util.JSON#encode JSON encoded}, along with
18 * the associated {@link Ext.data.Store}'s {@link Ext.data.Store#baseParams baseParams}, into the POST body.</p>
19 * <p>When using {@link Ext.data.DirectProxy}, set this to <tt>false</tt> since Ext.Direct.JsonProvider will perform
20 * its own json-encoding. In addition, if you're using {@link Ext.data.HttpProxy}, setting to <tt>false</tt>
21 * will cause HttpProxy to transmit data using the <b>jsonData</b> configuration-params of {@link Ext.Ajax#request}
22 * instead of <b>params</b>.</p>
23 * <p>When using a {@link Ext.data.Store#restful} Store, some serverside frameworks are
24 * tuned to expect data through the jsonData mechanism. In those cases, one will want to set <b>encode: <tt>false</tt></b>, as in
25 * let the lower-level connection object (eg: Ext.Ajax) do the encoding.</p>
29 * @cfg {Boolean} encodeDelete False to send only the id to the server on delete, true to encode it in an object
30 * literal, eg: <pre><code>
32 * </code></pre> Defaults to <tt>false</tt>
36 constructor : function(config){
37 Ext.data.JsonWriter.superclass.constructor.call(this, config);
41 * <p>This method should not need to be called by application code, however it may be useful on occasion to
42 * override it, or augment it with an {@link Function#createInterceptor interceptor} or {@link Function#createSequence sequence}.</p>
43 * <p>The provided implementation encodes the serialized data representing the Store's modified Records into the Ajax request's
44 * <code>params</code> according to the <code>{@link #encode}</code> setting.</p>
45 * @param {Object} Ajax request params object to write into.
46 * @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}.
47 * @param {Object/Object[]} data Data object representing the serialized modified records from the Store. May be either a single object,
48 * or an Array of objects - user implementations must handle both cases.
50 render : function(params, baseParams, data) {
51 if (this.encode === true) {
53 Ext.apply(params, baseParams);
54 params[this.meta.root] = Ext.encode(data);
56 // defer encoding for some other layer, probably in {@link Ext.Ajax#request}. Place everything into "jsonData" key.
57 var jdata = Ext.apply({}, baseParams);
58 jdata[this.meta.root] = data;
59 params.jsonData = jdata;
63 * Implements abstract Ext.data.DataWriter#createRecord
65 * @param {Ext.data.Record} rec
68 createRecord : function(rec) {
69 return this.toHash(rec);
72 * Implements abstract Ext.data.DataWriter#updateRecord
74 * @param {Ext.data.Record} rec
77 updateRecord : function(rec) {
78 return this.toHash(rec);
82 * Implements abstract Ext.data.DataWriter#destroyRecord
84 * @param {Ext.data.Record} rec
87 destroyRecord : function(rec){
88 if(this.encodeDelete){
90 data[this.meta.idProperty] = rec.id;
97 * @class Ext.data.JsonReader
98 * @extends Ext.data.DataReader
99 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
100 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
102 * <p>Example code:</p>
104 var myReader = new Ext.data.JsonReader({
105 // metadata configuration options:
106 {@link #idProperty}: 'id'
107 {@link #root}: 'rows',
108 {@link #totalProperty}: 'results',
109 {@link Ext.data.DataReader#messageProperty}: "msg" // The element within the response that provides a user-feedback message (optional)
111 // the fields config option will internally create an {@link Ext.data.Record}
112 // constructor that provides mapping for reading the record data objects
113 {@link Ext.data.DataReader#fields fields}: [
114 // map Record's 'firstname' field to data object's key of same name
115 {name: 'name', mapping: 'firstname'},
116 // map Record's 'job' field to data object's 'occupation' key
117 {name: 'job', mapping: 'occupation'}
121 * <p>This would consume a JSON data object of the form:</p><pre><code>
123 results: 2000, // Reader's configured {@link #totalProperty}
124 rows: [ // Reader's configured {@link #root}
125 // record data objects:
126 { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
127 { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
132 * <p><b><u>Automatic configuration using metaData</u></b></p>
133 * <p>It is possible to change a JsonReader's metadata at any time by including
134 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
135 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
136 * object using this Reader will reconfigure itself to use the newly provided
137 * field definition and fire its {@link Ext.data.Store#metachange metachange}
138 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
139 * property to perform any configuration required.</p>
140 * <p>Note that reconfiguring a Store potentially invalidates objects which may
141 * refer to Fields or Records which no longer exist.</p>
142 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
143 var myReader = new Ext.data.JsonReader();
145 * <p>The first data packet from the server would configure the reader by
146 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
147 * example, the JSON data object might take the form:</p><pre><code>
150 "{@link #idProperty}": "id",
151 "{@link #root}": "rows",
152 "{@link #totalProperty}": "results"
153 "{@link #successProperty}": "success",
154 "{@link Ext.data.DataReader#fields fields}": [
156 {"name": "job", "mapping": "occupation"}
158 // used by store to set its sortInfo
163 // {@link Ext.PagingToolbar paging data} (if applicable)
169 // Reader's configured {@link #successProperty}
171 // Reader's configured {@link #totalProperty}
173 // Reader's configured {@link #root}
174 // (this data simulates 2 results {@link Ext.PagingToolbar per page})
175 "rows": [ // <b>*Note:</b> this must be an Array
176 { "id": 1, "name": "Bill", "occupation": "Gardener" },
177 { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }
181 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
182 * <div class="mdetail-params"><ul>
183 * <li>any of the configuration options for this class</li>
184 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
185 * the JsonReader will use as an argument to the
186 * {@link Ext.data.Record#create data Record create method} in order to
187 * configure the layout of the Records it will produce.</li>
188 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
189 * which the JsonReader will use to set the {@link Ext.data.Store}'s
190 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
191 * <li>any custom properties needed</li>
195 * Create a new JsonReader
196 * @param {Object} meta Metadata configuration options.
197 * @param {Array/Object} recordType
198 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
199 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
200 * constructor created from {@link Ext.data.Record#create}.</p>
202 Ext.data.JsonReader = function(meta, recordType){
205 * @cfg {String} idProperty [id] Name of the property within a row object
206 * that contains a record identifier value. Defaults to <tt>id</tt>
209 * @cfg {String} successProperty [success] Name of the property from which to
210 * retrieve the success attribute. Defaults to <tt>success</tt>. See
211 * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
212 * for additional information.
215 * @cfg {String} totalProperty [total] Name of the property from which to
216 * retrieve the total number of records in the dataset. This is only needed
217 * if the whole dataset is not passed in one go, but is being paged from
218 * the remote server. Defaults to <tt>total</tt>.
221 * @cfg {String} root [undefined] <b>Required</b>. The name of the property
222 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
223 * An exception will be thrown if the root property is undefined. The data
224 * packet value for this property should be an empty array to clear the data
229 successProperty: 'success',
230 totalProperty: 'total'
233 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
235 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
237 * This JsonReader's metadata as passed to the constructor, or as passed in
238 * the last data packet's <b><tt>metaData</tt></b> property.
243 * This method is only used by a DataProxy which has retrieved data from a remote server.
244 * @param {Object} response The XHR object which contains the JSON data in its responseText.
245 * @return {Object} data A data block which is used by an Ext.data.Store object as
246 * a cache of Ext.data.Records.
248 read : function(response){
249 var json = response.responseText;
250 var o = Ext.decode(json);
252 throw {message: 'JsonReader.read: Json object not found'};
254 return this.readRecords(o);
258 * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
259 * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
262 * Decode a JSON response from server.
263 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
264 * @param {Object} response The XHR object returned through an Ajax server request.
265 * @return {Response} A {@link Ext.data.Response Response} object containing the data response, and also status information.
267 readResponse : function(action, response) {
268 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
270 throw new Ext.data.JsonReader.Error('response');
273 var root = this.getRoot(o);
274 if (action === Ext.data.Api.actions.create) {
275 var def = Ext.isDefined(root);
276 if (def && Ext.isEmpty(root)) {
277 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
280 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
284 // instantiate response object
285 var res = new Ext.data.Response({
287 success: this.getSuccess(o),
288 data: (root) ? this.extractData(root, false) : [],
289 message: this.getMessage(o),
293 // blow up if no successProperty
294 if (Ext.isEmpty(res.success)) {
295 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
301 * Create a data block containing Ext.data.Records from a JSON object.
302 * @param {Object} o An object which contains an Array of row objects in the property specified
303 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
304 * which contains the total size of the dataset.
305 * @return {Object} data A data block which is used by an Ext.data.Store object as
306 * a cache of Ext.data.Records.
308 readRecords : function(o){
310 * After any data loads, the raw JSON data is available for further custom processing. If no data is
311 * loaded or there is a load exception this property will be undefined.
316 this.onMetaChange(o.metaData);
318 var s = this.meta, Record = this.recordType,
319 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
321 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
323 v = parseInt(this.getTotal(o), 10);
328 if(s.successProperty){
329 v = this.getSuccess(o);
330 if(v === false || v === 'false'){
335 // TODO return Ext.data.Response instance instead. @see #readResponse
338 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
339 totalRecords : totalRecords
344 buildExtractors : function() {
348 var s = this.meta, Record = this.recordType,
349 f = Record.prototype.fields, fi = f.items, fl = f.length;
351 if(s.totalProperty) {
352 this.getTotal = this.createAccessor(s.totalProperty);
354 if(s.successProperty) {
355 this.getSuccess = this.createAccessor(s.successProperty);
357 if (s.messageProperty) {
358 this.getMessage = this.createAccessor(s.messageProperty);
360 this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
361 if (s.id || s.idProperty) {
362 var g = this.createAccessor(s.id || s.idProperty);
363 this.getId = function(rec) {
365 return (r === undefined || r === '') ? null : r;
368 this.getId = function(){return null;};
371 for(var i = 0; i < fl; i++){
373 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
374 ef.push(this.createAccessor(map));
381 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
383 simpleAccess : function(obj, subsc) {
390 createAccessor : function(){
392 return function(expr) {
393 if(Ext.isEmpty(expr)){
396 if(Ext.isFunction(expr)){
399 var i = String(expr).search(re);
401 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
403 return function(obj){
411 * type-casts a single row of raw-data from server
412 * @param {Object} data
413 * @param {Array} items
414 * @param {Integer} len
417 extractValues : function(data, items, len) {
419 for(var j = 0; j < len; j++){
421 var v = this.ef[j](data);
422 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
429 * @class Ext.data.JsonReader.Error
430 * Error class for JsonReader
432 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
433 constructor : function(message, arg) {
435 Ext.Error.call(this, message);
437 name : 'Ext.data.JsonReader'
439 Ext.apply(Ext.data.JsonReader.Error.prototype, {
441 'response': 'An error occurred while json-decoding your server response',
442 '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.',
443 '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.',
444 '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.',
445 '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.'
449 * @class Ext.data.ArrayReader
450 * @extends Ext.data.JsonReader
451 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an Array.
452 * Each element of that Array represents a row of data fields. The
453 * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
454 * of the field definition if it exists, or the field's ordinal position in the definition.</p>
455 * <p>Example code:</p>
457 var Employee = Ext.data.Record.create([
458 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
459 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
461 var myReader = new Ext.data.ArrayReader({
465 * <p>This would consume an Array like this:</p>
467 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
470 * Create a new ArrayReader
471 * @param {Object} meta Metadata configuration options.
472 * @param {Array/Object} recordType
473 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
474 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
475 * constructor created from {@link Ext.data.Record#create}.</p>
477 Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
479 * @cfg {String} successProperty
483 * @cfg {Number} id (optional) The subscript within row Array that provides an ID for the Record.
484 * Deprecated. Use {@link #idIndex} instead.
487 * @cfg {Number} idIndex (optional) The subscript within row Array that provides an ID for the Record.
490 * Create a data block containing Ext.data.Records from an Array.
491 * @param {Object} o An Array of row objects which represents the dataset.
492 * @return {Object} data A data block which is used by an Ext.data.Store object as
493 * a cache of Ext.data.Records.
495 readRecords : function(o){
498 sid = s ? Ext.num(s.idIndex, s.id) : null,
499 recordType = this.recordType,
500 fields = recordType.prototype.fields,
505 var root = this.getRoot(o);
507 for(var i = 0, len = root.length; i < len; i++) {
510 id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
511 for(var j = 0, jlen = fields.length; j < jlen; j++) {
512 var f = fields.items[j],
513 k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
514 v = n[k] !== undefined ? n[k] : f.defaultValue;
518 var record = new recordType(values, id);
520 records[records.length] = record;
523 var totalRecords = records.length;
525 if(s.totalProperty) {
526 v = parseInt(this.getTotal(o), 10);
531 if(s.successProperty){
532 v = this.getSuccess(o);
533 if(v === false || v === 'false'){
541 totalRecords : totalRecords
545 * @class Ext.data.ArrayStore
546 * @extends Ext.data.Store
547 * <p>Formerly known as "SimpleStore".</p>
548 * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
549 * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p>
550 * <p>A store configuration would be something like:<pre><code>
551 var store = new Ext.data.ArrayStore({
559 {name: 'price', type: 'float'},
560 {name: 'change', type: 'float'},
561 {name: 'pctChange', type: 'float'},
562 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
566 * <p>This store is configured to consume a returned object of the form:<pre><code>
568 ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
569 ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
570 ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
571 ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
572 ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
575 * An object literal of this form could also be used as the {@link #data} config option.</p>
576 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
577 * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p>
579 * @param {Object} config
582 Ext.data.ArrayStore = Ext.extend(Ext.data.Store, {
584 * @cfg {Ext.data.DataReader} reader @hide
586 constructor: function(config){
587 Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
588 reader: new Ext.data.ArrayReader(config)
592 loadData : function(data, append){
593 if(this.expandData === true){
595 for(var i = 0, len = data.length; i < len; i++){
596 r[r.length] = [data[i]];
600 Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
603 Ext.reg('arraystore', Ext.data.ArrayStore);
606 Ext.data.SimpleStore = Ext.data.ArrayStore;
607 Ext.reg('simplestore', Ext.data.SimpleStore);/**
608 * @class Ext.data.JsonStore
609 * @extends Ext.data.Store
610 * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
611 * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
612 * <p>A store configuration would be something like:<pre><code>
613 var store = new Ext.data.JsonStore({
616 url: 'get-images.php',
621 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
624 * <p>This store is configured to consume a returned object of the form:<pre><code>
627 {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
628 {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
632 * An object literal of this form could also be used as the {@link #data} config option.</p>
633 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
634 * <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
636 * @param {Object} config
639 Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
641 * @cfg {Ext.data.DataReader} reader @hide
643 constructor: function(config){
644 Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
645 reader: new Ext.data.JsonReader(config)
649 Ext.reg('jsonstore', Ext.data.JsonStore);