Upgrade to ExtJS 3.2.1 - Released 04/27/2010
[extjs.git] / src / data / XmlReader.js
1 /*!
2  * Ext JS Library 3.2.1
3  * Copyright(c) 2006-2010 Ext JS, Inc.
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 or id / success
63     Ext.applyIf(meta, {
64         idProperty: meta.idProperty || meta.idPath || meta.id,
65         successProperty: meta.successProperty || meta.success
66     });
67
68     Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
69 };
70 Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
71     /**
72      * This method is only used by a DataProxy which has retrieved data from a remote server.
73      * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
74      * to contain a property called <tt>responseXML</tt> which refers to an XML document object.
75      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
76      * a cache of Ext.data.Records.
77      */
78     read : function(response){
79         var doc = response.responseXML;
80         if(!doc) {
81             throw {message: "XmlReader.read: XML Document not available"};
82         }
83         return this.readRecords(doc);
84     },
85
86     /**
87      * Create a data block containing Ext.data.Records from an XML document.
88      * @param {Object} doc A parsed XML document.
89      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
90      * a cache of Ext.data.Records.
91      */
92     readRecords : function(doc){
93         /**
94          * After any data loads/reads, the raw XML Document is available for further custom processing.
95          * @type XMLDocument
96          */
97         this.xmlData = doc;
98
99         var root    = doc.documentElement || doc,
100             q       = Ext.DomQuery,
101             totalRecords = 0,
102             success = true;
103
104         if(this.meta.totalProperty){
105             totalRecords = this.getTotal(root, 0);
106         }
107         if(this.meta.successProperty){
108             success = this.getSuccess(root);
109         }
110
111         var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]
112
113         // TODO return Ext.data.Response instance.  @see #readResponse
114         return {
115             success : success,
116             records : records,
117             totalRecords : totalRecords || records.length
118         };
119     },
120
121     /**
122      * Decode an XML response from server.
123      * @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
124      * @param {Object} response HTTP Response object from browser.
125      * @return {Ext.data.Response} An instance of {@link Ext.data.Response}
126      */
127     readResponse : function(action, response) {
128         var q   = Ext.DomQuery,
129         doc     = response.responseXML;
130
131         // create general Response instance.
132         var res = new Ext.data.Response({
133             action: action,
134             success : this.getSuccess(doc),
135             message: this.getMessage(doc),
136             data: this.extractData(q.select(this.meta.record, doc) || q.select(this.meta.root, doc), false),
137             raw: doc
138         });
139
140         if (Ext.isEmpty(res.success)) {
141             throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
142         }
143
144         // Create actions from a response having status 200 must return pk
145         if (action === Ext.data.Api.actions.create) {
146             var def = Ext.isDefined(res.data);
147             if (def && Ext.isEmpty(res.data)) {
148                 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
149             }
150             else if (!def) {
151                 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
152             }
153         }
154         return res;
155     },
156
157     getSuccess : function() {
158         return true;
159     },
160
161     /**
162      * build response-data extractor functions.
163      * @private
164      * @ignore
165      */
166     buildExtractors : function() {
167         if(this.ef){
168             return;
169         }
170         var s       = this.meta,
171             Record  = this.recordType,
172             f       = Record.prototype.fields,
173             fi      = f.items,
174             fl      = f.length;
175
176         if(s.totalProperty) {
177             this.getTotal = this.createAccessor(s.totalProperty);
178         }
179         if(s.successProperty) {
180             this.getSuccess = this.createAccessor(s.successProperty);
181         }
182         if (s.messageProperty) {
183             this.getMessage = this.createAccessor(s.messageProperty);
184         }
185         this.getRoot = function(res) {
186             return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
187         };
188         if (s.idPath || s.idProperty) {
189             var g = this.createAccessor(s.idPath || s.idProperty);
190             this.getId = function(rec) {
191                 var id = g(rec) || rec.id;
192                 return (id === undefined || id === '') ? null : id;
193             };
194         } else {
195             this.getId = function(){return null;};
196         }
197         var ef = [];
198         for(var i = 0; i < fl; i++){
199             f = fi[i];
200             var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
201             ef.push(this.createAccessor(map));
202         }
203         this.ef = ef;
204     },
205
206     /**
207      * Creates a function to return some particular key of data from a response.
208      * @param {String} key
209      * @return {Function}
210      * @private
211      * @ignore
212      */
213     createAccessor : function(){
214         var q = Ext.DomQuery;
215         return function(key) {
216             switch(key) {
217                 case this.meta.totalProperty:
218                     return function(root, def){
219                         return q.selectNumber(key, root, def);
220                     };
221                     break;
222                 case this.meta.successProperty:
223                     return function(root, def) {
224                         var sv = q.selectValue(key, root, true);
225                         var success = sv !== false && sv !== 'false';
226                         return success;
227                     };
228                     break;
229                 default:
230                     return function(root, def) {
231                         return q.selectValue(key, root, def);
232                     };
233                     break;
234             }
235         };
236     }(),
237
238     /**
239      * extracts values and type-casts a row of data from server, extracted by #extractData
240      * @param {Hash} data
241      * @param {Ext.data.Field[]} items
242      * @param {Number} len
243      * @private
244      * @ignore
245      */
246     extractValues : function(data, items, len) {
247         var f, values = {};
248         for(var j = 0; j < len; j++){
249             f = items[j];
250             var v = this.ef[j](data);
251             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
252         }
253         return values;
254     }
255 });