3 * Copyright(c) 2006-2010 Ext JS, Inc.
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 = Ext.extend(Ext.data.DataWriter, {
14 * @cfg {Boolean} encode <tt>true</tt> to {@link Ext.util.JSON#encode encode} the
15 * {@link Ext.data.DataWriter#toHash hashed data}. Defaults to <tt>true</tt>. When using
16 * {@link Ext.data.DirectProxy}, set this to <tt>false</tt> since Ext.Direct.JsonProvider will perform
17 * its own json-encoding. In addition, if you're using {@link Ext.data.HttpProxy}, setting to <tt>false</tt>
18 * will cause HttpProxy to transmit data using the <b>jsonData</b> configuration-params of {@link Ext.Ajax#request}
19 * instead of <b>params</b>. When using a {@link Ext.data.Store#restful} Store, some serverside frameworks are
20 * tuned to expect data through the jsonData mechanism. In those cases, one will want to set <b>encode: <tt>false</tt></b>, as in
21 * let the lower-level connection object (eg: Ext.Ajax) do the encoding.
25 * @cfg {Boolean} encodeDelete False to send only the id to the server on delete, true to encode it in an object
26 * literal, eg: <pre><code>
28 * </code></pre> Defaults to <tt>false</tt>
32 constructor : function(config){
33 Ext.data.JsonWriter.superclass.constructor.call(this, config);
37 * Final action of a write event. Apply the written data-object to params.
38 * @param {Object} http params-object to write-to.
39 * @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}.
40 * @param {Object/Object[]} data Data-object representing compiled Store-recordset.
42 render : function(params, baseParams, data) {
43 if (this.encode === true) {
45 Ext.apply(params, baseParams);
46 params[this.meta.root] = Ext.encode(data);
48 // defer encoding for some other layer, probably in {@link Ext.Ajax#request}. Place everything into "jsonData" key.
49 var jdata = Ext.apply({}, baseParams);
50 jdata[this.meta.root] = data;
51 params.jsonData = jdata;
55 * Implements abstract Ext.data.DataWriter#createRecord
57 * @param {Ext.data.Record} rec
60 createRecord : function(rec) {
61 return this.toHash(rec);
64 * Implements abstract Ext.data.DataWriter#updateRecord
66 * @param {Ext.data.Record} rec
69 updateRecord : function(rec) {
70 return this.toHash(rec);
74 * Implements abstract Ext.data.DataWriter#destroyRecord
76 * @param {Ext.data.Record} rec
79 destroyRecord : function(rec){
80 if(this.encodeDelete){
82 data[this.meta.idProperty] = rec.id;
89 * @class Ext.data.JsonReader
90 * @extends Ext.data.DataReader
91 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
92 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
94 * <p>Example code:</p>
96 var myReader = new Ext.data.JsonReader({
97 // metadata configuration options:
98 {@link #idProperty}: 'id'
99 {@link #root}: 'rows',
100 {@link #totalProperty}: 'results',
101 {@link Ext.data.DataReader#messageProperty}: "msg" // The element within the response that provides a user-feedback message (optional)
103 // the fields config option will internally create an {@link Ext.data.Record}
104 // constructor that provides mapping for reading the record data objects
105 {@link Ext.data.DataReader#fields fields}: [
106 // map Record's 'firstname' field to data object's key of same name
108 // map Record's 'job' field to data object's 'occupation' key
109 {name: 'job', mapping: 'occupation'}
113 * <p>This would consume a JSON data object of the form:</p><pre><code>
115 results: 2000, // Reader's configured {@link #totalProperty}
116 rows: [ // Reader's configured {@link #root}
117 // record data objects:
118 { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
119 { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
124 * <p><b><u>Automatic configuration using metaData</u></b></p>
125 * <p>It is possible to change a JsonReader's metadata at any time by including
126 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
127 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
128 * object using this Reader will reconfigure itself to use the newly provided
129 * field definition and fire its {@link Ext.data.Store#metachange metachange}
130 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
131 * property to perform any configuration required.</p>
132 * <p>Note that reconfiguring a Store potentially invalidates objects which may
133 * refer to Fields or Records which no longer exist.</p>
134 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
135 var myReader = new Ext.data.JsonReader();
137 * <p>The first data packet from the server would configure the reader by
138 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
139 * example, the JSON data object might take the form:</p><pre><code>
142 "{@link #idProperty}": "id",
143 "{@link #root}": "rows",
144 "{@link #totalProperty}": "results"
145 "{@link #successProperty}": "success",
146 "{@link Ext.data.DataReader#fields fields}": [
148 {"name": "job", "mapping": "occupation"}
150 // used by store to set its sortInfo
155 // {@link Ext.PagingToolbar paging data} (if applicable)
161 // Reader's configured {@link #successProperty}
163 // Reader's configured {@link #totalProperty}
165 // Reader's configured {@link #root}
166 // (this data simulates 2 results {@link Ext.PagingToolbar per page})
167 "rows": [ // <b>*Note:</b> this must be an Array
168 { "id": 1, "name": "Bill", "occupation": "Gardener" },
169 { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }
173 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
174 * <div class="mdetail-params"><ul>
175 * <li>any of the configuration options for this class</li>
176 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
177 * the JsonReader will use as an argument to the
178 * {@link Ext.data.Record#create data Record create method} in order to
179 * configure the layout of the Records it will produce.</li>
180 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
181 * which the JsonReader will use to set the {@link Ext.data.Store}'s
182 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
183 * <li>any custom properties needed</li>
187 * Create a new JsonReader
188 * @param {Object} meta Metadata configuration options.
189 * @param {Array/Object} recordType
190 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
191 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
192 * constructor created from {@link Ext.data.Record#create}.</p>
194 Ext.data.JsonReader = function(meta, recordType){
197 * @cfg {String} idProperty [id] Name of the property within a row object
198 * that contains a record identifier value. Defaults to <tt>id</tt>
201 * @cfg {String} successProperty [success] Name of the property from which to
202 * retrieve the success attribute. Defaults to <tt>success</tt>. See
203 * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
204 * for additional information.
207 * @cfg {String} totalProperty [total] Name of the property from which to
208 * retrieve the total number of records in the dataset. This is only needed
209 * if the whole dataset is not passed in one go, but is being paged from
210 * the remote server. Defaults to <tt>total</tt>.
213 * @cfg {String} root [undefined] <b>Required</b>. The name of the property
214 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
215 * An exception will be thrown if the root property is undefined. The data
216 * packet value for this property should be an empty array to clear the data
221 successProperty: 'success',
222 totalProperty: 'total'
225 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
227 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
229 * This JsonReader's metadata as passed to the constructor, or as passed in
230 * the last data packet's <b><tt>metaData</tt></b> property.
235 * This method is only used by a DataProxy which has retrieved data from a remote server.
236 * @param {Object} response The XHR object which contains the JSON data in its responseText.
237 * @return {Object} data A data block which is used by an Ext.data.Store object as
238 * a cache of Ext.data.Records.
240 read : function(response){
241 var json = response.responseText;
242 var o = Ext.decode(json);
244 throw {message: 'JsonReader.read: Json object not found'};
246 return this.readRecords(o);
250 * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
251 * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
254 * Decode a JSON response from server.
255 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
256 * @param {Object} response The XHR object returned through an Ajax server request.
257 * @return {Response} A {@link Ext.data.Response Response} object containing the data response, and also status information.
259 readResponse : function(action, response) {
260 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
262 throw new Ext.data.JsonReader.Error('response');
265 var root = this.getRoot(o);
266 if (action === Ext.data.Api.actions.create) {
267 var def = Ext.isDefined(root);
268 if (def && Ext.isEmpty(root)) {
269 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
272 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
276 // instantiate response object
277 var res = new Ext.data.Response({
279 success: this.getSuccess(o),
280 data: (root) ? this.extractData(root, false) : [],
281 message: this.getMessage(o),
285 // blow up if no successProperty
286 if (Ext.isEmpty(res.success)) {
287 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
293 * Create a data block containing Ext.data.Records from a JSON object.
294 * @param {Object} o An object which contains an Array of row objects in the property specified
295 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
296 * which contains the total size of the dataset.
297 * @return {Object} data A data block which is used by an Ext.data.Store object as
298 * a cache of Ext.data.Records.
300 readRecords : function(o){
302 * After any data loads, the raw JSON data is available for further custom processing. If no data is
303 * loaded or there is a load exception this property will be undefined.
308 this.onMetaChange(o.metaData);
310 var s = this.meta, Record = this.recordType,
311 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
313 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
315 v = parseInt(this.getTotal(o), 10);
320 if(s.successProperty){
321 v = this.getSuccess(o);
322 if(v === false || v === 'false'){
327 // TODO return Ext.data.Response instance instead. @see #readResponse
330 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
331 totalRecords : totalRecords
336 buildExtractors : function() {
340 var s = this.meta, Record = this.recordType,
341 f = Record.prototype.fields, fi = f.items, fl = f.length;
343 if(s.totalProperty) {
344 this.getTotal = this.createAccessor(s.totalProperty);
346 if(s.successProperty) {
347 this.getSuccess = this.createAccessor(s.successProperty);
349 if (s.messageProperty) {
350 this.getMessage = this.createAccessor(s.messageProperty);
352 this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
353 if (s.id || s.idProperty) {
354 var g = this.createAccessor(s.id || s.idProperty);
355 this.getId = function(rec) {
357 return (r === undefined || r === '') ? null : r;
360 this.getId = function(){return null;};
363 for(var i = 0; i < fl; i++){
365 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
366 ef.push(this.createAccessor(map));
373 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
375 simpleAccess : function(obj, subsc) {
382 createAccessor : function(){
384 return function(expr) {
385 if(Ext.isEmpty(expr)){
388 if(Ext.isFunction(expr)){
391 var i = String(expr).search(re);
393 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
395 return function(obj){
403 * type-casts a single row of raw-data from server
404 * @param {Object} data
405 * @param {Array} items
406 * @param {Integer} len
409 extractValues : function(data, items, len) {
411 for(var j = 0; j < len; j++){
413 var v = this.ef[j](data);
414 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
421 * @class Ext.data.JsonReader.Error
422 * Error class for JsonReader
424 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
425 constructor : function(message, arg) {
427 Ext.Error.call(this, message);
429 name : 'Ext.data.JsonReader'
431 Ext.apply(Ext.data.JsonReader.Error.prototype, {
433 'response': 'An error occurred while json-decoding your server response',
434 '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.',
435 '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.',
436 '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.',
437 '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.'
441 * @class Ext.data.ArrayReader
442 * @extends Ext.data.JsonReader
443 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an Array.
444 * Each element of that Array represents a row of data fields. The
445 * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
446 * of the field definition if it exists, or the field's ordinal position in the definition.</p>
447 * <p>Example code:</p>
449 var Employee = Ext.data.Record.create([
450 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
451 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
453 var myReader = new Ext.data.ArrayReader({
457 * <p>This would consume an Array like this:</p>
459 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
462 * Create a new ArrayReader
463 * @param {Object} meta Metadata configuration options.
464 * @param {Array/Object} recordType
465 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
466 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
467 * constructor created from {@link Ext.data.Record#create}.</p>
469 Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
471 * @cfg {String} successProperty
475 * @cfg {Number} id (optional) The subscript within row Array that provides an ID for the Record.
476 * Deprecated. Use {@link #idIndex} instead.
479 * @cfg {Number} idIndex (optional) The subscript within row Array that provides an ID for the Record.
482 * Create a data block containing Ext.data.Records from an Array.
483 * @param {Object} o An Array of row objects which represents the dataset.
484 * @return {Object} data A data block which is used by an Ext.data.Store object as
485 * a cache of Ext.data.Records.
487 readRecords : function(o){
490 sid = s ? Ext.num(s.idIndex, s.id) : null,
491 recordType = this.recordType,
492 fields = recordType.prototype.fields,
497 var root = this.getRoot(o);
499 for(var i = 0, len = root.length; i < len; i++) {
502 id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
503 for(var j = 0, jlen = fields.length; j < jlen; j++) {
504 var f = fields.items[j],
505 k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
506 v = n[k] !== undefined ? n[k] : f.defaultValue;
510 var record = new recordType(values, id);
512 records[records.length] = record;
515 var totalRecords = records.length;
517 if(s.totalProperty) {
518 v = parseInt(this.getTotal(o), 10);
523 if(s.successProperty){
524 v = this.getSuccess(o);
525 if(v === false || v === 'false'){
533 totalRecords : totalRecords
537 * @class Ext.data.ArrayStore
538 * @extends Ext.data.Store
539 * <p>Formerly known as "SimpleStore".</p>
540 * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
541 * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p>
542 * <p>A store configuration would be something like:<pre><code>
543 var store = new Ext.data.ArrayStore({
551 {name: 'price', type: 'float'},
552 {name: 'change', type: 'float'},
553 {name: 'pctChange', type: 'float'},
554 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
558 * <p>This store is configured to consume a returned object of the form:<pre><code>
560 ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
561 ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
562 ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
563 ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
564 ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
567 * An object literal of this form could also be used as the {@link #data} config option.</p>
568 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
569 * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p>
571 * @param {Object} config
574 Ext.data.ArrayStore = Ext.extend(Ext.data.Store, {
576 * @cfg {Ext.data.DataReader} reader @hide
578 constructor: function(config){
579 Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
580 reader: new Ext.data.ArrayReader(config)
584 loadData : function(data, append){
585 if(this.expandData === true){
587 for(var i = 0, len = data.length; i < len; i++){
588 r[r.length] = [data[i]];
592 Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
595 Ext.reg('arraystore', Ext.data.ArrayStore);
598 Ext.data.SimpleStore = Ext.data.ArrayStore;
599 Ext.reg('simplestore', Ext.data.SimpleStore);/**
600 * @class Ext.data.JsonStore
601 * @extends Ext.data.Store
602 * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
603 * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
604 * <p>A store configuration would be something like:<pre><code>
605 var store = new Ext.data.JsonStore({
608 url: 'get-images.php',
613 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
616 * <p>This store is configured to consume a returned object of the form:<pre><code>
619 {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
620 {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
624 * An object literal of this form could also be used as the {@link #data} config option.</p>
625 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
626 * <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
628 * @param {Object} config
631 Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
633 * @cfg {Ext.data.DataReader} reader @hide
635 constructor: function(config){
636 Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
637 reader: new Ext.data.JsonReader(config)
641 Ext.reg('jsonstore', Ext.data.JsonStore);