Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / data / XmlReader.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.XmlReader
9  * @extends Ext.data.DataReader
10  * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
11  * based on mappings in a provided {@link Ext.data.Record} constructor.</p>
12  * <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
13  * header in the HTTP response must be set to "text/xml" or "application/xml".</p>
14  * <p>Example code:</p>
15  * <pre><code>
16 var Employee = Ext.data.Record.create([
17    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it is the same as "name"
18    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
19 ]);
20 var myReader = new Ext.data.XmlReader({
21    totalProperty: "results", // The element which contains the total dataset size (optional)
22    record: "row",           // The repeated element which contains row information
23    idProperty: "id"         // The element within the row that provides an ID for the record (optional)
24    messageProperty: "msg"   // The element within the response that provides a user-feedback message (optional)
25 }, Employee);
26 </code></pre>
27  * <p>
28  * This would consume an XML file like this:
29  * <pre><code>
30 &lt;?xml version="1.0" encoding="UTF-8"?>
31 &lt;dataset>
32  &lt;results>2&lt;/results>
33  &lt;row>
34    &lt;id>1&lt;/id>
35    &lt;name>Bill&lt;/name>
36    &lt;occupation>Gardener&lt;/occupation>
37  &lt;/row>
38  &lt;row>
39    &lt;id>2&lt;/id>
40    &lt;name>Ben&lt;/name>
41    &lt;occupation>Horticulturalist&lt;/occupation>
42  &lt;/row>
43 &lt;/dataset>
44 </code></pre>
45  * @cfg {String} totalProperty The DomQuery path from which to retrieve the total number of records
46  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
47  * paged from the remote server.
48  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
49  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
50  * @cfg {String} successProperty The DomQuery path to the success attribute used by forms.
51  * @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
52  * a record identifier value.
53  * @constructor
54  * Create a new XmlReader.
55  * @param {Object} meta Metadata configuration options
56  * @param {Object} recordType Either an Array of field definition objects as passed to
57  * {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
58  */
59 Ext.data.XmlReader = function(meta, recordType){
60     meta = meta || {};
61
62     // backwards compat, convert idPath to idProperty
63     meta.idProperty = meta.idProperty || meta.idPath;
64
65     Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
66 };
67 Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
68     /**
69      * This method is only used by a DataProxy which has retrieved data from a remote server.
70      * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
71      * to contain a property called <tt>responseXML</tt> which refers to an XML document object.
72      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
73      * a cache of Ext.data.Records.
74      */
75     read : function(response){
76         var doc = response.responseXML;
77         if(!doc) {
78             throw {message: "XmlReader.read: XML Document not available"};
79         }
80         return this.readRecords(doc);
81     },
82
83     /**
84      * Create a data block containing Ext.data.Records from an XML document.
85      * @param {Object} doc A parsed XML document.
86      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
87      * a cache of Ext.data.Records.
88      */
89     readRecords : function(doc){
90         /**
91          * After any data loads/reads, the raw XML Document is available for further custom processing.
92          * @type XMLDocument
93          */
94         this.xmlData = doc;
95
96         var root    = doc.documentElement || doc,
97             q       = Ext.DomQuery,
98             totalRecords = 0,
99             success = true;
100
101         if(this.meta.totalProperty){
102             totalRecords = this.getTotal(root, 0);
103         }
104         if(this.meta.successProperty){
105             success = this.getSuccess(root);
106         }
107
108         var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]
109
110         // TODO return Ext.data.Response instance.  @see #readResponse
111         return {
112             success : success,
113             records : records,
114             totalRecords : totalRecords || records.length
115         };
116     },
117
118     /**
119      * Decode a json response from server.
120      * @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
121      * @param {Ext.data.Response} response Returns an instance of {@link Ext.data.Response}
122      */
123     readResponse : function(action, response) {
124         var q   = Ext.DomQuery,
125         doc     = response.responseXML;
126
127         var res = new Ext.data.Response({
128             action: action,
129             success : this.getSuccess(doc),
130             message: this.getMessage(doc),
131             data: this.extractData(q.select(this.meta.record, doc) || q.select(this.meta.root, doc)),
132             raw: doc
133         });
134
135         if (Ext.isEmpty(res.success)) {
136             throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
137         }
138
139         if (action === Ext.data.Api.actions.create) {
140             var def = Ext.isDefined(res.data);
141             if (def && Ext.isEmpty(res.data)) {
142                 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
143             }
144             else if (!def) {
145                 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
146             }
147         }
148         return res;
149     },
150
151     getSuccess : function() {
152         return true;
153     },
154
155     /**
156      * build response-data extractor functions.
157      * @private
158      * @ignore
159      */
160     buildExtractors : function() {
161         if(this.ef){
162             return;
163         }
164         var s       = this.meta,
165             Record  = this.recordType,
166             f       = Record.prototype.fields,
167             fi      = f.items,
168             fl      = f.length;
169
170         if(s.totalProperty) {
171             this.getTotal = this.createAccessor(s.totalProperty);
172         }
173         if(s.successProperty) {
174             this.getSuccess = this.createAccessor(s.successProperty);
175         }
176         if (s.messageProperty) {
177             this.getMessage = this.createAccessor(s.messageProperty);
178         }
179         this.getRoot = function(res) {
180             return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
181         }
182         if (s.idPath || s.idProperty) {
183             var g = this.createAccessor(s.idPath || s.idProperty);
184             this.getId = function(rec) {
185                 var id = g(rec) || rec.id;
186                 return (id === undefined || id === '') ? null : id;
187             };
188         } else {
189             this.getId = function(){return null;};
190         }
191         var ef = [];
192         for(var i = 0; i < fl; i++){
193             f = fi[i];
194             var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
195             ef.push(this.createAccessor(map));
196         }
197         this.ef = ef;
198     },
199
200     /**
201      * Creates a function to return some particular key of data from a response.
202      * @param {String} key
203      * @return {Function}
204      * @private
205      * @ignore
206      */
207     createAccessor : function(){
208         var q = Ext.DomQuery;
209         return function(key) {
210             switch(key) {
211                 case this.meta.totalProperty:
212                     return function(root, def){
213                         return q.selectNumber(key, root, def);
214                     }
215                     break;
216                 case this.meta.successProperty:
217                     return function(root, def) {
218                         var sv = q.selectValue(key, root, true);
219                         var success = sv !== false && sv !== 'false';
220                         return success;
221                     }
222                     break;
223                 default:
224                     return function(root, def) {
225                         return q.selectValue(key, root, def);
226                     }
227                     break;
228             }
229         };
230     }(),
231
232     /**
233      * Extracts rows of record-data from server.  iterates and calls #extractValues
234      * TODO I don't care much for method-names of #extractData, #extractValues.
235      * @param {Array} root
236      * @param {Boolean} returnRecords When true, will return instances of Ext.data.Record; otherwise just hashes.
237      * @private
238      * @ignore
239      */
240     extractData : function(root, returnRecords) {
241         var Record  = this.recordType,
242         records     = [],
243         f           = Record.prototype.fields,
244         fi          = f.items,
245         fl          = f.length;
246         if (returnRecords === true) {
247             for (var i = 0, len = root.length; i < len; i++) {
248                 var data = root[i],
249                     record = new Record(this.extractValues(data, fi, fl), this.getId(data));
250                     
251                 record.node = data;
252                 records.push(record);
253             }
254         } else {
255             for (var i = 0, len = root.length; i < len; i++) {
256                 records.push(this.extractValues(root[i], fi, fl));
257             }
258         }
259         return records;
260     },
261
262     /**
263      * extracts values and type-casts a row of data from server, extracted by #extractData
264      * @param {Hash} data
265      * @param {Ext.data.Field[]} items
266      * @param {Number} len
267      * @private
268      * @ignore
269      */
270     extractValues : function(data, items, len) {
271         var f, values = {};
272         for(var j = 0; j < len; j++){
273             f = items[j];
274             var v = this.ef[j](data);
275             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
276         }
277         return values;
278     }
279 });