3 * Copyright(c) 2006-2010 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 = 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 * Decode a json response from server.
251 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
252 * @param {Object} response
253 * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
254 * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
256 readResponse : function(action, response) {
257 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
259 throw new Ext.data.JsonReader.Error('response');
262 var root = this.getRoot(o);
263 if (action === Ext.data.Api.actions.create) {
264 var def = Ext.isDefined(root);
265 if (def && Ext.isEmpty(root)) {
266 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
269 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
273 // instantiate response object
274 var res = new Ext.data.Response({
276 success: this.getSuccess(o),
277 data: (root) ? this.extractData(root, false) : [],
278 message: this.getMessage(o),
282 // blow up if no successProperty
283 if (Ext.isEmpty(res.success)) {
284 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
290 * Create a data block containing Ext.data.Records from a JSON object.
291 * @param {Object} o An object which contains an Array of row objects in the property specified
292 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
293 * which contains the total size of the dataset.
294 * @return {Object} data A data block which is used by an Ext.data.Store object as
295 * a cache of Ext.data.Records.
297 readRecords : function(o){
299 * After any data loads, the raw JSON data is available for further custom processing. If no data is
300 * loaded or there is a load exception this property will be undefined.
305 this.onMetaChange(o.metaData);
307 var s = this.meta, Record = this.recordType,
308 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
310 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
312 v = parseInt(this.getTotal(o), 10);
317 if(s.successProperty){
318 v = this.getSuccess(o);
319 if(v === false || v === 'false'){
324 // TODO return Ext.data.Response instance instead. @see #readResponse
327 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
328 totalRecords : totalRecords
333 buildExtractors : function() {
337 var s = this.meta, Record = this.recordType,
338 f = Record.prototype.fields, fi = f.items, fl = f.length;
340 if(s.totalProperty) {
341 this.getTotal = this.createAccessor(s.totalProperty);
343 if(s.successProperty) {
344 this.getSuccess = this.createAccessor(s.successProperty);
346 if (s.messageProperty) {
347 this.getMessage = this.createAccessor(s.messageProperty);
349 this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
350 if (s.id || s.idProperty) {
351 var g = this.createAccessor(s.id || s.idProperty);
352 this.getId = function(rec) {
354 return (r === undefined || r === '') ? null : r;
357 this.getId = function(){return null;};
360 for(var i = 0; i < fl; i++){
362 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
363 ef.push(this.createAccessor(map));
370 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
372 simpleAccess : function(obj, subsc) {
379 createAccessor : function(){
381 return function(expr) {
382 if(Ext.isEmpty(expr)){
385 if(Ext.isFunction(expr)){
388 var i = String(expr).search(re);
390 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
392 return function(obj){
400 * type-casts a single row of raw-data from server
401 * @param {Object} data
402 * @param {Array} items
403 * @param {Integer} len
406 extractValues : function(data, items, len) {
408 for(var j = 0; j < len; j++){
410 var v = this.ef[j](data);
411 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
418 * @class Ext.data.JsonReader.Error
419 * Error class for JsonReader
421 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
422 constructor : function(message, arg) {
424 Ext.Error.call(this, message);
426 name : 'Ext.data.JsonReader'
428 Ext.apply(Ext.data.JsonReader.Error.prototype, {
430 'response': 'An error occurred while json-decoding your server response',
431 '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.',
432 '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.',
433 '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.',
434 '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.'
438 * @class Ext.data.ArrayReader
439 * @extends Ext.data.JsonReader
440 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an Array.
441 * Each element of that Array represents a row of data fields. The
442 * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
443 * of the field definition if it exists, or the field's ordinal position in the definition.</p>
444 * <p>Example code:</p>
446 var Employee = Ext.data.Record.create([
447 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
448 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
450 var myReader = new Ext.data.ArrayReader({
454 * <p>This would consume an Array like this:</p>
456 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
459 * Create a new ArrayReader
460 * @param {Object} meta Metadata configuration options.
461 * @param {Array/Object} recordType
462 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
463 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
464 * constructor created from {@link Ext.data.Record#create}.</p>
466 Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
468 * @cfg {String} successProperty
472 * @cfg {Number} id (optional) The subscript within row Array that provides an ID for the Record.
473 * Deprecated. Use {@link #idIndex} instead.
476 * @cfg {Number} idIndex (optional) The subscript within row Array that provides an ID for the Record.
479 * Create a data block containing Ext.data.Records from an Array.
480 * @param {Object} o An Array of row objects which represents the dataset.
481 * @return {Object} data A data block which is used by an Ext.data.Store object as
482 * a cache of Ext.data.Records.
484 readRecords : function(o){
487 sid = s ? Ext.num(s.idIndex, s.id) : null,
488 recordType = this.recordType,
489 fields = recordType.prototype.fields,
494 var root = this.getRoot(o);
496 for(var i = 0, len = root.length; i < len; i++) {
499 id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
500 for(var j = 0, jlen = fields.length; j < jlen; j++) {
501 var f = fields.items[j],
502 k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
503 v = n[k] !== undefined ? n[k] : f.defaultValue;
507 var record = new recordType(values, id);
509 records[records.length] = record;
512 var totalRecords = records.length;
514 if(s.totalProperty) {
515 v = parseInt(this.getTotal(o), 10);
520 if(s.successProperty){
521 v = this.getSuccess(o);
522 if(v === false || v === 'false'){
530 totalRecords : totalRecords
534 * @class Ext.data.ArrayStore
535 * @extends Ext.data.Store
536 * <p>Formerly known as "SimpleStore".</p>
537 * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
538 * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p>
539 * <p>A store configuration would be something like:<pre><code>
540 var store = new Ext.data.ArrayStore({
548 {name: 'price', type: 'float'},
549 {name: 'change', type: 'float'},
550 {name: 'pctChange', type: 'float'},
551 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
555 * <p>This store is configured to consume a returned object of the form:<pre><code>
557 ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
558 ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
559 ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
560 ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
561 ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
564 * An object literal of this form could also be used as the {@link #data} config option.</p>
565 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
566 * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p>
568 * @param {Object} config
571 Ext.data.ArrayStore = Ext.extend(Ext.data.Store, {
573 * @cfg {Ext.data.DataReader} reader @hide
575 constructor: function(config){
576 Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
577 reader: new Ext.data.ArrayReader(config)
581 loadData : function(data, append){
582 if(this.expandData === true){
584 for(var i = 0, len = data.length; i < len; i++){
585 r[r.length] = [data[i]];
589 Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
592 Ext.reg('arraystore', Ext.data.ArrayStore);
595 Ext.data.SimpleStore = Ext.data.ArrayStore;
596 Ext.reg('simplestore', Ext.data.SimpleStore);/**
597 * @class Ext.data.JsonStore
598 * @extends Ext.data.Store
599 * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
600 * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
601 * <p>A store configuration would be something like:<pre><code>
602 var store = new Ext.data.JsonStore({
605 url: 'get-images.php',
610 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
613 * <p>This store is configured to consume a returned object of the form:<pre><code>
616 {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
617 {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
621 * An object literal of this form could also be used as the {@link #data} config option.</p>
622 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
623 * <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
625 * @param {Object} config
628 Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
630 * @cfg {Ext.data.DataReader} reader @hide
632 constructor: function(config){
633 Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
634 reader: new Ext.data.JsonReader(config)
638 Ext.reg('jsonstore', Ext.data.JsonStore);