3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
8 * @class Ext.data.XmlWriter
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 via XML.
12 Ext.data.XmlWriter = function(params) {
13 Ext.data.XmlWriter.superclass.constructor.apply(this, arguments);
14 this.tpl = new Ext.XTemplate(this.tpl).compile();
16 Ext.extend(Ext.data.XmlWriter, Ext.data.DataWriter, {
18 * @cfg {String} root [records] The name of the root element when writing <b>multiple</b> records to the server. Each
19 * xml-record written to the server will be wrapped in an element named after {@link Ext.data.XmlReader#record} property.
22 <?xml version="1.0" encoding="UTF-8"?>
23 <user><first>Barney</first></user>
25 * However, when <b>multiple</b> records are written in a batch-operation, these records must be wrapped in a containing
29 <?xml version="1.0" encoding="UTF-8"?>
31 <first>Barney</first></user>
32 <records><first>Barney</first></user>
35 * Defaults to <tt>records</tt>
39 * @cfg {String} xmlVersion [1.0] The <tt>version</tt> written to header of xml documents.
40 <code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
44 * @cfg {String} xmlEncoding [ISO-8859-15] The <tt>encoding</tt> written to header of xml documents.
45 <code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
47 xmlEncoding: 'ISO-8859-15',
49 * @cfg {String} tpl The xml template. Defaults to
51 <?xml version="{version}" encoding="{encoding}"?>
52 <tpl if="{[values.nodes.length>1]}"><{root}}>',
53 <tpl for="records">
56 <{name}>{value}</{name}>
60 <tpl if="{[values.records.length>1]}"></{root}}></tpl>
63 // Break up encoding here in case it's being included by some kind of page that will parse it (eg. PHP)
64 tpl: '<tpl for="."><' + '?xml version="{version}" encoding="{encoding}"?' + '><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}</tpl></tpl></tpl><tpl if="records.length>1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length>1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',
67 * Final action of a write event. Apply the written data-object to params.
68 * @param {String} action [Ext.data.Api.create|read|update|destroy]
69 * @param {Ext.data.Record/Ext.data.Record[]} rs
70 * @param {Object} http params
71 * @param {Object/Object[]} rendered data.
73 render : function(action, rs, params, data) {
74 params.xmlData = this.tpl.applyTemplate({
75 version: this.xmlVersion,
76 encoding: this.xmlEncoding,
77 record: this.meta.record,
79 records: (Ext.isArray(rs)) ? data : [data]
84 * Converts an Ext.data.Record to xml
85 * @param {Ext.data.Record} rec
86 * @return {String} rendered xml-element
89 toXml : function(data) {
91 Ext.iterate(data, function(k, v) {
104 * @param {Ext.data.Record} rec
105 * @return {String} xml element
108 createRecord : function(rec) {
109 return this.toXml(this.toHash(rec));
114 * @param {Ext.data.Record} rec
115 * @return {String} xml element
118 updateRecord : function(rec) {
119 return this.toXml(this.toHash(rec));
124 * @param {Ext.data.Record} rec
125 * @return {String} xml element
127 destroyRecord : function(rec) {
129 data[this.meta.idProperty] = rec.id;
130 return this.toXml(data);
135 * @class Ext.data.XmlReader
136 * @extends Ext.data.DataReader
137 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
138 * based on mappings in a provided {@link Ext.data.Record} constructor.</p>
139 * <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
140 * header in the HTTP response must be set to "text/xml" or "application/xml".</p>
141 * <p>Example code:</p>
143 var Employee = Ext.data.Record.create([
144 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it is the same as "name"
145 {name: 'occupation'} // This field will use "occupation" as the mapping.
147 var myReader = new Ext.data.XmlReader({
148 totalProperty: "results", // The element which contains the total dataset size (optional)
149 record: "row", // The repeated element which contains row information
150 idProperty: "id" // The element within the row that provides an ID for the record (optional)
151 messageProperty: "msg" // The element within the response that provides a user-feedback message (optional)
155 * This would consume an XML file like this:
157 <?xml version="1.0" encoding="UTF-8"?>
159 <results>2</results>
162 <name>Bill</name>
163 <occupation>Gardener</occupation>
167 <name>Ben</name>
168 <occupation>Horticulturalist</occupation>
172 * @cfg {String} totalProperty The DomQuery path from which to retrieve the total number of records
173 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
174 * paged from the remote server.
175 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
176 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
177 * @cfg {String} successProperty The DomQuery path to the success attribute used by forms.
178 * @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
179 * a record identifier value.
181 * Create a new XmlReader.
182 * @param {Object} meta Metadata configuration options
183 * @param {Object} recordType Either an Array of field definition objects as passed to
184 * {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
186 Ext.data.XmlReader = function(meta, recordType){
189 // backwards compat, convert idPath to idProperty
190 meta.idProperty = meta.idProperty || meta.idPath;
192 Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
194 Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
196 * This method is only used by a DataProxy which has retrieved data from a remote server.
197 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
198 * to contain a property called <tt>responseXML</tt> which refers to an XML document object.
199 * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
200 * a cache of Ext.data.Records.
202 read : function(response){
203 var doc = response.responseXML;
205 throw {message: "XmlReader.read: XML Document not available"};
207 return this.readRecords(doc);
211 * Create a data block containing Ext.data.Records from an XML document.
212 * @param {Object} doc A parsed XML document.
213 * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
214 * a cache of Ext.data.Records.
216 readRecords : function(doc){
218 * After any data loads/reads, the raw XML Document is available for further custom processing.
223 var root = doc.documentElement || doc,
228 if(this.meta.totalProperty){
229 totalRecords = this.getTotal(root, 0);
231 if(this.meta.successProperty){
232 success = this.getSuccess(root);
235 var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]
237 // TODO return Ext.data.Response instance. @see #readResponse
241 totalRecords : totalRecords || records.length
246 * Decode a json response from server.
247 * @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
248 * @param {Ext.data.Response} response Returns an instance of {@link Ext.data.Response}
250 readResponse : function(action, response) {
251 var q = Ext.DomQuery,
252 doc = response.responseXML;
254 var res = new Ext.data.Response({
256 success : this.getSuccess(doc),
257 message: this.getMessage(doc),
258 data: this.extractData(q.select(this.meta.record, doc) || q.select(this.meta.root, doc)),
262 if (Ext.isEmpty(res.success)) {
263 throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
266 if (action === Ext.data.Api.actions.create) {
267 var def = Ext.isDefined(res.data);
268 if (def && Ext.isEmpty(res.data)) {
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);
278 getSuccess : function() {
283 * build response-data extractor functions.
287 buildExtractors : function() {
292 Record = this.recordType,
293 f = Record.prototype.fields,
297 if(s.totalProperty) {
298 this.getTotal = this.createAccessor(s.totalProperty);
300 if(s.successProperty) {
301 this.getSuccess = this.createAccessor(s.successProperty);
303 if (s.messageProperty) {
304 this.getMessage = this.createAccessor(s.messageProperty);
306 this.getRoot = function(res) {
307 return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
309 if (s.idPath || s.idProperty) {
310 var g = this.createAccessor(s.idPath || s.idProperty);
311 this.getId = function(rec) {
312 var id = g(rec) || rec.id;
313 return (id === undefined || id === '') ? null : id;
316 this.getId = function(){return null;};
319 for(var i = 0; i < fl; i++){
321 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
322 ef.push(this.createAccessor(map));
328 * Creates a function to return some particular key of data from a response.
329 * @param {String} key
334 createAccessor : function(){
335 var q = Ext.DomQuery;
336 return function(key) {
338 case this.meta.totalProperty:
339 return function(root, def){
340 return q.selectNumber(key, root, def);
343 case this.meta.successProperty:
344 return function(root, def) {
345 var sv = q.selectValue(key, root, true);
346 var success = sv !== false && sv !== 'false';
351 return function(root, def) {
352 return q.selectValue(key, root, def);
360 * Extracts rows of record-data from server. iterates and calls #extractValues
361 * TODO I don't care much for method-names of #extractData, #extractValues.
362 * @param {Array} root
363 * @param {Boolean} returnRecords When true, will return instances of Ext.data.Record; otherwise just hashes.
367 extractData : function(root, returnRecords) {
368 var Record = this.recordType,
370 f = Record.prototype.fields,
373 if (returnRecords === true) {
374 for (var i = 0, len = root.length; i < len; i++) {
376 record = new Record(this.extractValues(data, fi, fl), this.getId(data));
379 records.push(record);
382 for (var i = 0, len = root.length; i < len; i++) {
383 records.push(this.extractValues(root[i], fi, fl));
390 * extracts values and type-casts a row of data from server, extracted by #extractData
392 * @param {Ext.data.Field[]} items
393 * @param {Number} len
397 extractValues : function(data, items, len) {
399 for(var j = 0; j < len; j++){
401 var v = this.ef[j](data);
402 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
407 * @class Ext.data.XmlStore
\r
408 * @extends Ext.data.Store
\r
409 * <p>Small helper class to make creating {@link Ext.data.Store}s from XML data easier.
\r
410 * A XmlStore will be automatically configured with a {@link Ext.data.XmlReader}.</p>
\r
411 * <p>A store configuration would be something like:<pre><code>
\r
412 var store = new Ext.data.XmlStore({
\r
415 storeId: 'myStore',
\r
416 url: 'sheldon.xml', // automatically configures a HttpProxy
\r
418 record: 'Item', // records will have an "Item" tag
\r
420 totalRecords: '@TotalResults'
\r
422 // set up the fields mapping into the xml doc
\r
423 // The first needs mapping, the others are very basic
\r
424 {name: 'Author', mapping: 'ItemAttributes > Author'},
\r
425 'Title', 'Manufacturer', 'ProductGroup'
\r
428 * </code></pre></p>
\r
429 * <p>This store is configured to consume a returned object of the form:<pre><code>
\r
430 <?xml version="1.0" encoding="UTF-8"?>
\r
431 <ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15">
\r
434 <IsValid>True</IsValid>
\r
435 <ItemSearchRequest>
\r
436 <Author>Sidney Sheldon</Author>
\r
437 <SearchIndex>Books</SearchIndex>
\r
438 </ItemSearchRequest>
\r
440 <TotalResults>203</TotalResults>
\r
441 <TotalPages>21</TotalPages>
\r
443 <ASIN>0446355453</ASIN>
\r
445 http://www.amazon.com/
\r
446 </DetailPageURL>
\r
447 <ItemAttributes>
\r
448 <Author>Sidney Sheldon</Author>
\r
449 <Manufacturer>Warner Books</Manufacturer>
\r
450 <ProductGroup>Book</ProductGroup>
\r
451 <Title>Master of the Game</Title>
\r
452 </ItemAttributes>
\r
455 </ItemSearchResponse>
\r
457 * An object literal of this form could also be used as the {@link #data} config option.</p>
\r
458 * <p><b>Note:</b> Although not listed here, this class accepts all of the configuration options of
\r
459 * <b>{@link Ext.data.XmlReader XmlReader}</b>.</p>
\r
461 * @param {Object} config
\r
464 Ext.data.XmlStore = Ext.extend(Ext.data.Store, {
\r
466 * @cfg {Ext.data.DataReader} reader @hide
\r
468 constructor: function(config){
\r
469 Ext.data.XmlStore.superclass.constructor.call(this, Ext.apply(config, {
\r
470 reader: new Ext.data.XmlReader(config)
\r
474 Ext.reg('xmlstore', Ext.data.XmlStore);