3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
10 * Ext.data.Api is a singleton designed to manage the data API including methods
11 * for validating a developer's DataProxy API. Defines variables for CRUD actions
12 * create, read, update and destroy in addition to a mapping of RESTful HTTP methods
13 * GET, POST, PUT and DELETE to CRUD actions.
16 Ext.data.Api = (function() {
18 // private validActions. validActions is essentially an inverted hash of Ext.data.Api.actions, where value becomes the key.
19 // Some methods in this singleton (e.g.: getActions, getVerb) will loop through actions with the code <code>for (var verb in this.actions)</code>
20 // For efficiency, some methods will first check this hash for a match. Those methods which do acces validActions will cache their result here.
21 // We cannot pre-define this hash since the developer may over-ride the actions at runtime.
22 var validActions = {};
26 * Defined actions corresponding to remote actions:
29 create : 'create', // Text representing the remote-action to create records on server.
30 read : 'read', // Text representing the remote-action to read/load data from server.
31 update : 'update', // Text representing the remote-action to update records on server.
32 destroy : 'destroy' // Text representing the remote-action to destroy records on server.
46 * Defined {CRUD action}:{HTTP method} pairs to associate HTTP methods with the
47 * corresponding actions for {@link Ext.data.DataProxy#restful RESTful proxies}.
66 * Returns true if supplied action-name is a valid API action defined in <code>{@link #actions}</code> constants
67 * @param {String} action
68 * @param {String[]}(Optional) List of available CRUD actions. Pass in list when executing multiple times for efficiency.
71 isAction : function(action) {
72 return (Ext.data.Api.actions[action]) ? true : false;
76 * Returns the actual CRUD action KEY "create", "read", "update" or "destroy" from the supplied action-name. This method is used internally and shouldn't generally
77 * need to be used directly. The key/value pair of Ext.data.Api.actions will often be identical but this is not necessarily true. A developer can override this naming
78 * convention if desired. However, the framework internally calls methods based upon the KEY so a way of retreiving the the words "create", "read", "update" and "destroy" is
79 * required. This method will cache discovered KEYS into the private validActions hash.
80 * @param {String} name The runtime name of the action.
81 * @return {String||null} returns the action-key, or verb of the user-action or null if invalid.
84 getVerb : function(name) {
85 if (validActions[name]) {
86 return validActions[name]; // <-- found in cache. return immediately.
88 for (var verb in this.actions) {
89 if (this.actions[verb] === name) {
90 validActions[name] = verb;
94 return (validActions[name] !== undefined) ? validActions[name] : null;
98 * Returns true if the supplied API is valid; that is, check that all keys match defined actions
99 * otherwise returns an array of mistakes.
100 * @return {String[]||true}
102 isValid : function(api){
104 var crud = this.actions; // <-- cache a copy of the actions.
105 for (var action in api) {
106 if (!(action in crud)) {
107 invalid.push(action);
110 return (!invalid.length) ? true : invalid;
114 * Returns true if the supplied verb upon the supplied proxy points to a unique url in that none of the other api-actions
115 * point to the same url. The question is important for deciding whether to insert the "xaction" HTTP parameter within an
116 * Ajax request. This method is used internally and shouldn't generally need to be called directly.
117 * @param {Ext.data.DataProxy} proxy
118 * @param {String} verb
121 hasUniqueUrl : function(proxy, verb) {
122 var url = (proxy.api[verb]) ? proxy.api[verb].url : null;
124 for (var action in proxy.api) {
125 if ((unique = (action === verb) ? true : (proxy.api[action].url != url) ? true : false) === false) {
133 * This method is used internally by <tt>{@link Ext.data.DataProxy DataProxy}</tt> and should not generally need to be used directly.
134 * Each action of a DataProxy api can be initially defined as either a String or an Object. When specified as an object,
135 * one can explicitly define the HTTP method (GET|POST) to use for each CRUD action. This method will prepare the supplied API, setting
136 * each action to the Object form. If your API-actions do not explicitly define the HTTP method, the "method" configuration-parameter will
137 * be used. If the method configuration parameter is not specified, POST will be used.
139 new Ext.data.HttpProxy({
140 method: "POST", // <-- default HTTP method when not specified.
142 create: 'create.php',
145 destroy: 'destroy.php'
149 // Alternatively, one can use the object-form to specify the API
150 new Ext.data.HttpProxy({
152 load: {url: 'read.php', method: 'GET'},
153 create: 'create.php',
154 destroy: 'destroy.php',
160 * @param {Ext.data.DataProxy} proxy
162 prepare : function(proxy) {
164 proxy.api = {}; // <-- No api? create a blank one.
166 for (var verb in this.actions) {
167 var action = this.actions[verb];
168 proxy.api[action] = proxy.api[action] || proxy.url || proxy.directFn;
169 if (typeof(proxy.api[action]) == 'string') {
170 proxy.api[action] = {
171 url: proxy.api[action]
178 * Prepares a supplied Proxy to be RESTful. Sets the HTTP method for each api-action to be one of
179 * GET, POST, PUT, DELETE according to the defined {@link #restActions}.
180 * @param {Ext.data.DataProxy} proxy
182 restify : function(proxy) {
183 proxy.restful = true;
184 for (var verb in this.restActions) {
185 proxy.api[this.actions[verb]].method = this.restActions[verb];
192 * @class Ext.data.Api.Error
194 * Error class for Ext.data.Api errors
196 Ext.data.Api.Error = Ext.extend(Ext.Error, {
197 constructor : function(message, arg) {
199 Ext.Error.call(this, message);
203 Ext.apply(Ext.data.Api.Error.prototype, {
205 'action-url-undefined': 'No fallback url defined for this action. When defining a DataProxy api, please be sure to define an url for each CRUD action in Ext.data.Api.actions or define a default url in addition to your api-configuration.',
206 'invalid': 'received an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions',
207 'invalid-url': 'Invalid url. Please review your proxy configuration.',
208 'execute': 'Attempted to execute an unknown action. Valid API actions are defined in Ext.data.Api.actions"'
213 * @class Ext.data.SortTypes
\r
215 * Defines the default sorting (casting?) comparison functions used when sorting data.
\r
217 Ext.data.SortTypes = {
\r
219 * Default sort that does nothing
\r
220 * @param {Mixed} s The value being converted
\r
221 * @return {Mixed} The comparison value
\r
223 none : function(s){
\r
228 * The regular expression used to strip tags
\r
232 stripTagsRE : /<\/?[^>]+>/gi,
\r
235 * Strips all HTML tags to sort on text only
\r
236 * @param {Mixed} s The value being converted
\r
237 * @return {String} The comparison value
\r
239 asText : function(s){
\r
240 return String(s).replace(this.stripTagsRE, "");
\r
244 * Strips all HTML tags to sort on text only - Case insensitive
\r
245 * @param {Mixed} s The value being converted
\r
246 * @return {String} The comparison value
\r
248 asUCText : function(s){
\r
249 return String(s).toUpperCase().replace(this.stripTagsRE, "");
\r
253 * Case insensitive string
\r
254 * @param {Mixed} s The value being converted
\r
255 * @return {String} The comparison value
\r
257 asUCString : function(s) {
\r
258 return String(s).toUpperCase();
\r
263 * @param {Mixed} s The value being converted
\r
264 * @return {Number} The comparison value
\r
266 asDate : function(s) {
\r
271 return s.getTime();
\r
273 return Date.parse(String(s));
\r
278 * @param {Mixed} s The value being converted
\r
279 * @return {Float} The comparison value
\r
281 asFloat : function(s) {
\r
282 var val = parseFloat(String(s).replace(/,/g, ""));
\r
283 return isNaN(val) ? 0 : val;
\r
288 * @param {Mixed} s The value being converted
\r
289 * @return {Number} The comparison value
\r
291 asInt : function(s) {
\r
292 var val = parseInt(String(s).replace(/,/g, ""), 10);
\r
293 return isNaN(val) ? 0 : val;
\r
296 * @class Ext.data.Record
297 * <p>Instances of this class encapsulate both Record <em>definition</em> information, and Record
298 * <em>value</em> information for use in {@link Ext.data.Store} objects, or any code which needs
299 * to access Records cached in an {@link Ext.data.Store} object.</p>
300 * <p>Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
301 * Instances are usually only created by {@link Ext.data.Reader} implementations when processing unformatted data
303 * <p>Note that an instance of a Record class may only belong to one {@link Ext.data.Store Store} at a time.
304 * In order to copy data from one Store to another, use the {@link #copy} method to create an exact
305 * copy of the Record, and insert the new instance into the other Store.</p>
306 * <p>When serializing a Record for submission to the server, be aware that it contains many private
307 * properties, and also a reference to its owning Store which in turn holds references to its Records.
308 * This means that a whole Record may not be encoded using {@link Ext.util.JSON.encode}. Instead, use the
309 * <code>{@link #data}</code> and <code>{@link #id}</code> properties.</p>
310 * <p>Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.</p>
312 * This constructor should not be used to create Record objects. Instead, use {@link #create} to
313 * generate a subclass of Ext.data.Record configured with information about its constituent fields.
314 * @param {Object} data (Optional) An object, the properties of which provide values for the new Record's
315 * fields. If not specified the <code>{@link Ext.data.Field#defaultValue defaultValue}</code>
316 * for each field will be assigned.
317 * @param {Object} id (Optional) The id of the Record. This id should be unique, and is used by the
318 * {@link Ext.data.Store} object which owns the Record to index its collection of Records. If
319 * an <code>id</code> is not specified a <b><code>{@link #phantom}</code></b> Record will be created
320 * with an {@link #Record.id automatically generated id}.
322 Ext.data.Record = function(data, id){
323 // if no id, call the auto id method
324 this.id = (id || id === 0) ? id : Ext.data.Record.id(this);
325 this.data = data || {};
329 * Generate a constructor for a specific Record layout.
330 * @param {Array} o An Array of <b>{@link Ext.data.Field Field}</b> definition objects.
331 * The constructor generated by this method may be used to create new Record instances. The data
332 * object must contain properties named after the {@link Ext.data.Field field}
333 * <b><tt>{@link Ext.data.Field#name}s</tt></b>. Example usage:<pre><code>
334 // create a Record constructor from a description of the fields
335 var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
336 {{@link Ext.data.Field#name name}: 'title', {@link Ext.data.Field#mapping mapping}: 'topic_title'},
337 {name: 'author', mapping: 'username', allowBlank: false},
338 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
339 {name: 'lastPost', mapping: 'post_time', type: 'date'},
340 {name: 'lastPoster', mapping: 'user2'},
341 {name: 'excerpt', mapping: 'post_text', allowBlank: false},
342 // In the simplest case, if no properties other than <tt>name</tt> are required,
343 // a field definition may consist of just a String for the field name.
347 // create Record instance
348 var myNewRecord = new TopicRecord(
350 title: 'Do my job please',
353 lastPost: new Date(),
354 lastPoster: 'Animal',
355 excerpt: 'No way dude!',
358 id // optionally specify the id of the record otherwise {@link #Record.id one is auto-assigned}
360 myStore.{@link Ext.data.Store#add add}(myNewRecord);
363 * @return {function} A constructor which is used to create new Records according
364 * to the definition. The constructor has the same signature as {@link #Ext.data.Record}.
367 Ext.data.Record.create = function(o){
368 var f = Ext.extend(Ext.data.Record, {});
370 p.fields = new Ext.util.MixedCollection(false, function(field){
373 for(var i = 0, len = o.length; i < len; i++){
374 p.fields.add(new Ext.data.Field(o[i]));
376 f.getField = function(name){
377 return p.fields.get(name);
382 Ext.data.Record.PREFIX = 'ext-record';
383 Ext.data.Record.AUTO_ID = 1;
384 Ext.data.Record.EDIT = 'edit';
385 Ext.data.Record.REJECT = 'reject';
386 Ext.data.Record.COMMIT = 'commit';
390 * Generates a sequential id. This method is typically called when a record is {@link #create}d
391 * and {@link #Record no id has been specified}. The returned id takes the form:
392 * <tt>{PREFIX}-{AUTO_ID}</tt>.<div class="mdetail-params"><ul>
393 * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.PREFIX</tt>
394 * (defaults to <tt>'ext-record'</tt>)</p></li>
395 * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.AUTO_ID</tt>
396 * (defaults to <tt>1</tt> initially)</p></li>
398 * @param {Record} rec The record being created. The record does not exist, it's a {@link #phantom}.
399 * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
401 Ext.data.Record.id = function(rec) {
403 return [Ext.data.Record.PREFIX, '-', Ext.data.Record.AUTO_ID++].join('');
406 Ext.data.Record.prototype = {
408 * <p><b>This property is stored in the Record definition's <u>prototype</u></b></p>
409 * A MixedCollection containing the defined {@link Ext.data.Field Field}s for this Record. Read-only.
411 * @type Ext.util.MixedCollection
414 * An object hash representing the data for this Record. Every field name in the Record definition
415 * is represented by a property of that name in this object. Note that unless you specified a field
416 * with {@link Ext.data.Field#name name} "id" in the Record definition, this will <b>not</b> contain
417 * an <tt>id</tt> property.
422 * The unique ID of the Record {@link #Record as specified at construction time}.
427 * Readonly flag - true if this Record has been modified.
434 * This object contains a key and value storing the original values of all modified
435 * fields or is null if no fields have been modified.
441 * <tt>false</tt> when the record does not yet exist in a server-side database (see
442 * {@link #markDirty}). Any record which has a real database pk set as its id property
443 * is NOT a phantom -- it's real.
450 join : function(store){
452 * The {@link Ext.data.Store} to which this Record belongs.
454 * @type {Ext.data.Store}
460 * Set the {@link Ext.data.Field#name named field} to the specified value. For example:
462 // record has a field named 'firstname'
463 var Employee = Ext.data.Record.{@link #create}([
468 // update the 2nd record in the store:
469 var rec = myStore.{@link Ext.data.Store#getAt getAt}(1);
471 // set the value (shows dirty flag):
472 rec.set('firstname', 'Betty');
474 // commit the change (removes dirty flag):
475 rec.{@link #commit}();
477 // update the record in the store, bypass setting dirty flag,
478 // and do not store the change in the {@link Ext.data.Store#getModifiedRecords modified records}
479 rec.{@link #data}['firstname'] = 'Wilma'); // updates record, but not the view
480 rec.{@link #commit}(); // updates the view
482 * <b>Notes</b>:<div class="mdetail-params"><ul>
483 * <li>If the store has a writer and <code>autoSave=true</code>, each set()
484 * will execute an XHR to the server.</li>
485 * <li>Use <code>{@link #beginEdit}</code> to prevent the store's <code>update</code>
486 * event firing while using set().</li>
487 * <li>Use <code>{@link #endEdit}</code> to have the store's <code>update</code>
490 * @param {String} name The {@link Ext.data.Field#name name of the field} to set.
491 * @param {Object} value The value to set the field to.
493 set : function(name, value){
494 var isObj = (typeof value === 'object');
495 if(!isObj && String(this.data[name]) === String(value)){
497 } else if (isObj && Ext.encode(this.data[name]) === Ext.encode(value)) {
504 if(typeof this.modified[name] == 'undefined'){
505 this.modified[name] = this.data[name];
507 this.data[name] = value;
514 afterEdit: function(){
516 this.store.afterEdit(this);
521 afterReject: function(){
523 this.store.afterReject(this);
528 afterCommit: function(){
530 this.store.afterCommit(this);
535 * Get the value of the {@link Ext.data.Field#name named field}.
536 * @param {String} name The {@link Ext.data.Field#name name of the field} to get the value of.
537 * @return {Object} The value of the field.
539 get : function(name){
540 return this.data[name];
544 * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
545 * are relayed to the containing store.
546 * See also: <code>{@link #endEdit}</code> and <code>{@link #cancelEdit}</code>.
548 beginEdit : function(){
550 this.modified = this.modified || {};
554 * Cancels all changes made in the current edit operation.
556 cancelEdit : function(){
557 this.editing = false;
558 delete this.modified;
562 * End an edit. If any data was modified, the containing store is notified
563 * (ie, the store's <code>update</code> event will fire).
565 endEdit : function(){
566 this.editing = false;
573 * Usually called by the {@link Ext.data.Store} which owns the Record.
574 * Rejects all changes made to the Record since either creation, or the last commit operation.
575 * Modified fields are reverted to their original values.
576 * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
577 * to have their code notified of reject operations.</p>
578 * @param {Boolean} silent (optional) True to skip notification of the owning
579 * store of the change (defaults to false)
581 reject : function(silent){
582 var m = this.modified;
584 if(typeof m[n] != "function"){
589 delete this.modified;
590 this.editing = false;
597 * Usually called by the {@link Ext.data.Store} which owns the Record.
598 * Commits all changes made to the Record since either creation, or the last commit operation.
599 * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
600 * to have their code notified of commit operations.</p>
601 * @param {Boolean} silent (optional) True to skip notification of the owning
602 * store of the change (defaults to false)
604 commit : function(silent){
606 delete this.modified;
607 this.editing = false;
614 * Gets a hash of only the fields that have been modified since this Record was created or commited.
617 getChanges : function(){
618 var m = this.modified, cs = {};
620 if(m.hasOwnProperty(n)){
621 cs[n] = this.data[n];
628 hasError : function(){
629 return this.error !== null;
633 clearError : function(){
638 * Creates a copy of this Record.
639 * @param {String} id (optional) A new Record id, defaults to {@link #Record.id autogenerating an id}.
640 * Note: if an <code>id</code> is not specified the copy created will be a
641 * <code>{@link #phantom}</code> Record.
644 copy : function(newId) {
645 return new this.constructor(Ext.apply({}, this.data), newId || this.id);
649 * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
650 * since the load or last commit.
651 * @param {String} fieldName {@link Ext.data.Field.{@link Ext.data.Field#name}
654 isModified : function(fieldName){
655 return !!(this.modified && this.modified.hasOwnProperty(fieldName));
659 * By default returns <tt>false</tt> if any {@link Ext.data.Field field} within the
660 * record configured with <tt>{@link Ext.data.Field#allowBlank} = false</tt> returns
661 * <tt>true</tt> from an {@link Ext}.{@link Ext#isEmpty isempty} test.
664 isValid : function() {
665 return this.fields.find(function(f) {
666 return (f.allowBlank === false && Ext.isEmpty(this.data[f.name])) ? true : false;
667 },this) ? false : true;
671 * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>. This method
672 * is used interally when adding <code>{@link #phantom}</code> records to a
673 * {@link Ext.data.Store#writer writer enabled store}.</p>
674 * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
675 * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
676 * have a create action composed for it during {@link Ext.data.Store#save store save}
679 markDirty : function(){
684 this.fields.each(function(f) {
685 this.modified[f.name] = this.data[f.name];
689 * @class Ext.StoreMgr
690 * @extends Ext.util.MixedCollection
691 * The default global group of stores.
694 Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), {
696 * @cfg {Object} listeners @hide
700 * Registers one or more Stores with the StoreMgr. You do not normally need to register stores
701 * manually. Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered.
702 * @param {Ext.data.Store} store1 A Store instance
703 * @param {Ext.data.Store} store2 (optional)
704 * @param {Ext.data.Store} etc... (optional)
706 register : function(){
707 for(var i = 0, s; (s = arguments[i]); i++){
713 * Unregisters one or more Stores with the StoreMgr
714 * @param {String/Object} id1 The id of the Store, or a Store instance
715 * @param {String/Object} id2 (optional)
716 * @param {String/Object} etc... (optional)
718 unregister : function(){
719 for(var i = 0, s; (s = arguments[i]); i++){
720 this.remove(this.lookup(s));
725 * Gets a registered Store by id
726 * @param {String/Object} id The id of the Store, or a Store instance
727 * @return {Ext.data.Store}
729 lookup : function(id){
731 var fields = ['field1'], expand = !Ext.isArray(id[0]);
733 for(var i = 2, len = id[0].length; i <= len; ++i){
734 fields.push('field' + i);
737 return new Ext.data.ArrayStore({
746 return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id);
749 // getKey implementation for MixedCollection
750 getKey : function(o){
754 * @class Ext.data.Store
755 * @extends Ext.util.Observable
756 * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
757 * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
758 * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
759 * <p><u>Retrieving Data</u></p>
760 * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
761 * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
762 * <li>{@link #data} to automatically pass in data</li>
763 * <li>{@link #loadData} to manually pass in data</li>
765 * <p><u>Reading Data</u></p>
766 * <p>A Store object has no inherent knowledge of the format of the data object (it could be
767 * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
768 * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
770 * <p><u>Store Types</u></p>
771 * <p>There are several implementations of Store available which are customized for use with
772 * a specific DataReader implementation. Here is an example using an ArrayStore which implicitly
773 * creates a reader commensurate to an Array data object.</p>
775 var myStore = new Ext.data.ArrayStore({
776 fields: ['fullname', 'first'],
777 idIndex: 0 // id for each record will be the first element
780 * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
782 // create a {@link Ext.data.Record Record} constructor:
783 var rt = Ext.data.Record.create([
787 var myStore = new Ext.data.Store({
788 // explicitly create reader
789 reader: new Ext.data.ArrayReader(
791 idIndex: 0 // id for each record will be the first element
797 * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
800 [1, 'Fred Flintstone', 'Fred'], // note that id for the record is the first element
801 [2, 'Barney Rubble', 'Barney']
803 myStore.loadData(myData);
805 * <p>Records are cached and made available through accessor functions. An example of adding
806 * a record to the store:</p>
809 fullname: 'Full Name',
812 var recId = 100; // provide unique id for the record
813 var r = new myStore.recordType(defaultData, ++recId); // create new record
814 myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
817 * Creates a new Store.
818 * @param {Object} config A config object containing the objects needed for the Store to access data,
819 * and read the data into Records.
822 Ext.data.Store = function(config){
823 this.data = new Ext.util.MixedCollection(false);
824 this.data.getKey = function(o){
828 * See the <code>{@link #baseParams corresponding configuration option}</code>
829 * for a description of this property.
830 * To modify this property see <code>{@link #setBaseParam}</code>.
833 this.baseParams = {};
835 // temporary removed-records cache
838 if(config && config.data){
839 this.inlineData = config.data;
843 Ext.apply(this, config);
845 this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
847 if(this.url && !this.proxy){
848 this.proxy = new Ext.data.HttpProxy({url: this.url});
850 // If Store is RESTful, so too is the DataProxy
851 if (this.restful === true && this.proxy) {
852 // When operating RESTfully, a unique transaction is generated for each record.
854 Ext.data.Api.restify(this.proxy);
857 if(this.reader){ // reader passed
858 if(!this.recordType){
859 this.recordType = this.reader.recordType;
861 if(this.reader.onMetaChange){
862 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
864 if (this.writer) { // writer passed
865 this.writer.meta = this.reader.meta;
866 this.pruneModifiedRecords = true;
871 * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
872 * {@link Ext.data.DataReader Reader}. Read-only.
873 * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
874 * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
875 * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
876 * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
877 // create the data store
878 var store = new Ext.data.ArrayStore({
882 {name: 'price', type: 'float'},
883 {name: 'change', type: 'float'},
884 {name: 'pctChange', type: 'float'},
885 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
888 store.loadData(myData);
891 var grid = new Ext.grid.EditorGridPanel({
893 colModel: new Ext.grid.ColumnModel({
895 {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
896 {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
897 {header: 'Change', renderer: change, dataIndex: 'change'},
898 {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
899 {header: 'Last Updated', width: 85,
900 renderer: Ext.util.Format.dateRenderer('m/d/Y'),
901 dataIndex: 'lastChange'}
908 autoExpandColumn: 'company', // match the id specified in the column model
914 handler : function(){
917 company: 'New Company',
918 lastChange: (new Date()).clearTime(),
922 var recId = 3; // provide unique id
923 var p = new store.recordType(defaultData, recId); // create new record
925 store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
926 grid.startEditing(0, 0);
931 * @property recordType
937 * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
938 * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
940 * @type Ext.util.MixedCollection
942 this.fields = this.recordType.prototype.fields;
949 * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
950 * widget that is using this Store as a Record cache should refresh its view.
951 * @param {Store} this
956 * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
957 * @param {Store} this
958 * @param {Object} meta The JSON metadata
963 * Fires when Records have been {@link #add}ed to the Store
964 * @param {Store} this
965 * @param {Ext.data.Record[]} records The array of Records added
966 * @param {Number} index The index at which the record(s) were added
971 * Fires when a Record has been {@link #remove}d from the Store
972 * @param {Store} this
973 * @param {Ext.data.Record} record The Record that was removed
974 * @param {Number} index The index at which the record was removed
979 * Fires when a Record has been updated
980 * @param {Store} this
981 * @param {Ext.data.Record} record The Record that was updated
982 * @param {String} operation The update operation being performed. Value may be one of:
985 Ext.data.Record.REJECT
986 Ext.data.Record.COMMIT
992 * Fires when the data cache has been cleared.
993 * @param {Store} this
998 * <p>Fires if an exception occurs in the Proxy during a remote request.
999 * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
1000 * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
1001 * for additional details.
1002 * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
1008 * Fires before a request is made for a new data object. If the beforeload handler returns
1009 * <tt>false</tt> the {@link #load} action will be canceled.
1010 * @param {Store} this
1011 * @param {Object} options The loading options that were specified (see {@link #load} for details)
1016 * Fires after a new set of Records has been loaded.
1017 * @param {Store} this
1018 * @param {Ext.data.Record[]} records The Records that were loaded
1019 * @param {Object} options The loading options that were specified (see {@link #load} for details)
1023 * @event loadexception
1024 * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
1025 * event instead.</p>
1026 * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
1027 * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
1028 * for additional details.
1029 * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
1034 * @event beforewrite
1035 * @param {DataProxy} this
1036 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
1037 * @param {Record/Array[Record]} rs
1038 * @param {Object} options The loading options that were specified. Edit <code>options.params</code> to add Http parameters to the request. (see {@link #save} for details)
1039 * @param {Object} arg The callback's arg object passed to the {@link #request} function
1044 * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
1045 * Success or failure of the action is available in the <code>result['successProperty']</code> property.
1046 * The server-code might set the <code>successProperty</code> to <tt>false</tt> if a database validation
1047 * failed, for example.
1048 * @param {Ext.data.Store} store
1049 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
1050 * @param {Object} result The 'data' picked-out out of the response for convenience.
1051 * @param {Ext.Direct.Transaction} res
1052 * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
1058 this.relayEvents(this.proxy, ['loadexception', 'exception']);
1060 // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
1064 add: this.createRecords,
1065 remove: this.destroyRecord,
1066 update: this.updateRecord
1070 this.sortToggle = {};
1072 this.setDefaultSort(this.sortField, this.sortDir);
1073 }else if(this.sortInfo){
1074 this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
1077 Ext.data.Store.superclass.constructor.call(this);
1080 this.storeId = this.id;
1084 Ext.StoreMgr.register(this);
1086 if(this.inlineData){
1087 this.loadData(this.inlineData);
1088 delete this.inlineData;
1089 }else if(this.autoLoad){
1090 this.load.defer(10, this, [
1091 typeof this.autoLoad == 'object' ?
1092 this.autoLoad : undefined]);
1095 Ext.extend(Ext.data.Store, Ext.util.Observable, {
1097 * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
1098 * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
1102 * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
1103 * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
1104 * Typically this option, or the <code>{@link #data}</code> option will be specified.
1107 * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
1108 * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
1109 * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
1110 * be passed to the store's {@link #load} method.
1113 * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
1114 * access to a data object. See <code>{@link #url}</code>.
1117 * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
1118 * Typically this option, or the <code>{@link #url}</code> option will be specified.
1121 * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
1122 * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
1123 * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
1126 * @cfg {Ext.data.DataWriter} writer
1127 * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
1128 * to the server-side database.</p>
1129 * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
1130 * events on the store are monitored in order to remotely {@link #createRecords create records},
1131 * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
1132 * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
1133 * <br><p>Sample implementation:
1135 var writer = new {@link Ext.data.JsonWriter}({
1137 writeAllFields: true // write all fields, not just those that changed
1140 // Typical Store collecting the Proxy, Reader and Writer together.
1141 var store = new Ext.data.Store({
1146 writer: writer, // <-- plug a DataWriter into the store just as you would a Reader
1148 autoSave: false // <-- false to delay executing create, update, destroy requests
1149 // until specifically told to do so.
1155 * @cfg {Object} baseParams
1156 * <p>An object containing properties which are to be sent as parameters
1157 * for <i>every</i> HTTP request.</p>
1158 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
1159 * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
1160 * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
1161 * for more details.</p>
1162 * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
1167 * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
1168 * {@link #load} operation. Note that for local sorting, the <tt>direction</tt> property is
1169 * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
1170 * For example:<pre><code>
1173 direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
1178 * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
1179 * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
1180 * in place (defaults to <tt>false</tt>).
1181 * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
1182 * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
1183 * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
1184 * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
1185 * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
1186 * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
1192 * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
1193 * to is destroyed (defaults to <tt>false</tt>).
1194 * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
1196 autoDestroy : false,
1199 * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
1200 * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
1201 * for the accessor method to retrieve the modified records.
1203 pruneModifiedRecords : false,
1206 * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
1207 * for the details of what this may contain. This may be useful for accessing any params which were used
1208 * to load the current Record cache.
1214 * @cfg {Boolean} autoSave
1215 * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
1216 * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
1217 * to send all modifiedRecords to the server.</p>
1218 * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
1223 * @cfg {Boolean} batch
1224 * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
1225 * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
1226 * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
1227 * to <tt>false</tt>.</p>
1228 * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
1229 * generated for each record.</p>
1234 * @cfg {Boolean} restful
1235 * Defaults to <tt>false</tt>. Set to <tt>true</tt> to have the Store and the set
1236 * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
1237 * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
1238 * action is described in {@link Ext.data.Api#restActions}. For additional information
1239 * see {@link Ext.data.DataProxy#restful}.
1240 * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
1241 * internally be set to <tt>false</tt>.</p>
1246 * @cfg {Object} paramNames
1247 * <p>An object containing properties which specify the names of the paging and
1248 * sorting parameters passed to remote servers when loading blocks of data. By default, this
1249 * object takes the following form:</p><pre><code>
1251 start : 'start', // The parameter name which specifies the start row
1252 limit : 'limit', // The parameter name which specifies number of rows to return
1253 sort : 'sort', // The parameter name which specifies the column to sort on
1254 dir : 'dir' // The parameter name which specifies the sort direction
1257 * <p>The server must produce the requested data block upon receipt of these parameter names.
1258 * If different parameter names are required, this property can be overriden using a configuration
1260 * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
1261 * the parameter names to use in its {@link #load requests}.
1263 paramNames : undefined,
1266 * @cfg {Object} defaultParamNames
1267 * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
1268 * for all stores, this object should be changed on the store prototype.
1270 defaultParamNames : {
1278 * Destroys the store.
1280 destroy : function(){
1282 Ext.StoreMgr.unregister(this);
1285 Ext.destroy(this.proxy);
1286 this.reader = this.writer = null;
1287 this.purgeListeners();
1291 * Add Records to the Store and fires the {@link #add} event. To add Records
1292 * to the store from a remote source use <code>{@link #load}({add:true})</code>.
1293 * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
1294 * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
1295 * to add to the cache. See {@link #recordType}.
1297 add : function(records){
1298 records = [].concat(records);
1299 if(records.length < 1){
1302 for(var i = 0, len = records.length; i < len; i++){
1303 records[i].join(this);
1305 var index = this.data.length;
1306 this.data.addAll(records);
1308 this.snapshot.addAll(records);
1310 this.fireEvent('add', this, records, index);
1314 * (Local sort only) Inserts the passed Record into the Store at the index where it
1315 * should go based on the current sort information.
1316 * @param {Ext.data.Record} record
1318 addSorted : function(record){
1319 var index = this.findInsertIndex(record);
1320 this.insert(index, record);
1324 * Remove a Record from the Store and fires the {@link #remove} event.
1325 * @param {Ext.data.Record} record The Ext.data.Record object to remove from the cache.
1327 remove : function(record){
1328 var index = this.data.indexOf(record);
1330 this.data.removeAt(index);
1331 if(this.pruneModifiedRecords){
1332 this.modified.remove(record);
1335 this.snapshot.remove(record);
1337 this.fireEvent('remove', this, record, index);
1342 * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
1343 * @param {Number} index The index of the record to remove.
1345 removeAt : function(index){
1346 this.remove(this.getAt(index));
1350 * Remove all Records from the Store and fires the {@link #clear} event.
1352 removeAll : function(){
1355 this.snapshot.clear();
1357 if(this.pruneModifiedRecords){
1360 this.fireEvent('clear', this);
1364 * Inserts Records into the Store at the given index and fires the {@link #add} event.
1365 * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
1366 * @param {Number} index The start index at which to insert the passed Records.
1367 * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
1369 insert : function(index, records){
1370 records = [].concat(records);
1371 for(var i = 0, len = records.length; i < len; i++){
1372 this.data.insert(index, records[i]);
1373 records[i].join(this);
1375 this.fireEvent('add', this, records, index);
1379 * Get the index within the cache of the passed Record.
1380 * @param {Ext.data.Record} record The Ext.data.Record object to find.
1381 * @return {Number} The index of the passed Record. Returns -1 if not found.
1383 indexOf : function(record){
1384 return this.data.indexOf(record);
1388 * Get the index within the cache of the Record with the passed id.
1389 * @param {String} id The id of the Record to find.
1390 * @return {Number} The index of the Record. Returns -1 if not found.
1392 indexOfId : function(id){
1393 return this.data.indexOfKey(id);
1397 * Get the Record with the specified id.
1398 * @param {String} id The id of the Record to find.
1399 * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
1401 getById : function(id){
1402 return this.data.key(id);
1406 * Get the Record at the specified index.
1407 * @param {Number} index The index of the Record to find.
1408 * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
1410 getAt : function(index){
1411 return this.data.itemAt(index);
1415 * Returns a range of Records between specified indices.
1416 * @param {Number} startIndex (optional) The starting index (defaults to 0)
1417 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
1418 * @return {Ext.data.Record[]} An array of Records
1420 getRange : function(start, end){
1421 return this.data.getRange(start, end);
1425 storeOptions : function(o){
1426 o = Ext.apply({}, o);
1429 this.lastOptions = o;
1433 * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
1434 * <br><p>Notes:</p><div class="mdetail-params"><ul>
1435 * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
1436 * loaded. To perform any post-processing where information from the load call is required, specify
1437 * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
1438 * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
1439 * properties in the <code>options.params</code> property to establish the initial position within the
1440 * dataset, and the number of Records to cache on each read from the Proxy.</li>
1441 * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
1442 * will be automatically included with the posted parameters according to the specified
1443 * <code>{@link #paramNames}</code>.</li>
1445 * @param {Object} options An object containing properties which control loading options:<ul>
1446 * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
1447 * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
1448 * <code>{@link #baseParams}</code> of the same name.</p>
1449 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
1450 * <li><b><tt>callback</tt></b> : Function<div class="sub-desc"><p>A function to be called after the Records
1451 * have been loaded. The <tt>callback</tt> is called after the load event and is passed the following arguments:<ul>
1452 * <li><tt>r</tt> : Ext.data.Record[]</li>
1453 * <li><tt>options</tt>: Options object from the load call</li>
1454 * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div></li>
1455 * <li><b><tt>scope</tt></b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
1456 * to the Store object)</p></div></li>
1457 * <li><b><tt>add</tt></b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
1458 * replace the current cache. <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
1460 * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
1461 * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
1463 load : function(options) {
1464 options = options || {};
1465 this.storeOptions(options);
1466 if(this.sortInfo && this.remoteSort){
1467 var pn = this.paramNames;
1468 options.params = options.params || {};
1469 options.params[pn.sort] = this.sortInfo.field;
1470 options.params[pn.dir] = this.sortInfo.direction;
1473 return this.execute('read', null, options); // <-- null represents rs. No rs for load actions.
1475 this.handleException(e);
1481 * updateRecord Should not be used directly. This method will be called automatically if a Writer is set.
1482 * Listens to 'update' event.
1483 * @param {Object} store
1484 * @param {Object} record
1485 * @param {Object} action
1488 updateRecord : function(store, record, action) {
1489 if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid))) {
1495 * Should not be used directly. Store#add will call this automatically if a Writer is set
1496 * @param {Object} store
1497 * @param {Object} rs
1498 * @param {Object} index
1501 createRecords : function(store, rs, index) {
1502 for (var i = 0, len = rs.length; i < len; i++) {
1503 if (rs[i].phantom && rs[i].isValid()) {
1504 rs[i].markDirty(); // <-- Mark new records dirty
1505 this.modified.push(rs[i]); // <-- add to modified
1508 if (this.autoSave === true) {
1514 * Destroys a record or records. Should not be used directly. It's called by Store#remove if a Writer is set.
1515 * @param {Store} this
1516 * @param {Ext.data.Record/Ext.data.Record[]}
1517 * @param {Number} index
1520 destroyRecord : function(store, record, index) {
1521 if (this.modified.indexOf(record) != -1) { // <-- handled already if @cfg pruneModifiedRecords == true
1522 this.modified.remove(record);
1524 if (!record.phantom) {
1525 this.removed.push(record);
1527 // since the record has already been removed from the store but the server request has not yet been executed,
1528 // must keep track of the last known index this record existed. If a server error occurs, the record can be
1529 // put back into the store. @see Store#createCallback where the record is returned when response status === false
1530 record.lastIndex = index;
1532 if (this.autoSave === true) {
1539 * This method should generally not be used directly. This method is called internally
1540 * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
1541 * {@link #remove}, or {@link #update} events fire.
1542 * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
1543 * @param {Record/Record[]} rs
1544 * @param {Object} options
1548 execute : function(action, rs, options) {
1549 // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
1550 if (!Ext.data.Api.isAction(action)) {
1551 throw new Ext.data.Api.Error('execute', action);
1553 // make sure options has a params key
1554 options = Ext.applyIf(options||{}, {
1558 // have to separate before-events since load has a different signature than create,destroy and save events since load does not
1559 // include the rs (record resultset) parameter. Capture return values from the beforeaction into doRequest flag.
1560 var doRequest = true;
1562 if (action === 'read') {
1563 doRequest = this.fireEvent('beforeload', this, options);
1566 // if Writer is configured as listful, force single-recoord rs to be [{}} instead of {}
1567 if (this.writer.listful === true && this.restful !== true) {
1568 rs = (Ext.isArray(rs)) ? rs : [rs];
1570 // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
1571 else if (Ext.isArray(rs) && rs.length == 1) {
1574 // Write the action to options.params
1575 if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
1576 this.writer.write(action, options.params, rs);
1579 if (doRequest !== false) {
1580 // Send request to proxy.
1581 var params = Ext.apply({}, options.params, this.baseParams);
1582 if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
1583 params.xaction = action;
1585 // Note: Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions. We'll flip it now
1586 // and send the value into DataProxy#request, since it's the value which maps to the DataProxy#api
1587 this.proxy.request(Ext.data.Api.actions[action], rs, params, this.reader, this.createCallback(action, rs), this, options);
1593 * Saves all pending changes to the store. If the commensurate Ext.data.Api.actions action is not configured, then
1594 * the configured <code>{@link #url}</code> will be used.
1597 * --------------- --------------------
1598 * removed records Ext.data.Api.actions.destroy
1599 * phantom records Ext.data.Api.actions.create
1600 * {@link #getModifiedRecords modified records} Ext.data.Api.actions.update
1602 * @TODO: Create extensions of Error class and send associated Record with thrown exceptions.
1603 * e.g.: Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
1607 throw new Ext.data.Store.Error('writer-undefined');
1610 // DESTROY: First check for removed records. Records in this.removed are guaranteed non-phantoms. @see Store#remove
1611 if (this.removed.length) {
1612 this.doTransaction('destroy', this.removed);
1615 // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
1616 var rs = [].concat(this.getModifiedRecords());
1617 if (!rs.length) { // Bail-out if empty...
1621 // CREATE: Next check for phantoms within rs. splice-off and execute create.
1623 for (var i = rs.length-1; i >= 0; i--) {
1624 if (rs[i].phantom === true) {
1625 var rec = rs.splice(i, 1).shift();
1626 if (rec.isValid()) {
1629 } else if (!rs[i].isValid()) { // <-- while we're here, splice-off any !isValid real records
1633 // If we have valid phantoms, create them...
1634 if (phantoms.length) {
1635 this.doTransaction('create', phantoms);
1638 // UPDATE: And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
1640 this.doTransaction('update', rs);
1645 // private. Simply wraps call to Store#execute in try/catch. Defers to Store#handleException on error. Loops if batch: false
1646 doTransaction : function(action, rs) {
1647 function transaction(records) {
1649 this.execute(action, records);
1651 this.handleException(e);
1654 if (this.batch === false) {
1655 for (var i = 0, len = rs.length; i < len; i++) {
1656 transaction.call(this, rs[i]);
1659 transaction.call(this, rs);
1663 // @private callback-handler for remote CRUD actions
1664 // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
1665 createCallback : function(action, rs) {
1666 var actions = Ext.data.Api.actions;
1667 return (action == 'read') ? this.loadRecords : function(data, response, success) {
1668 // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
1669 this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, data);
1670 // If success === false here, exception will have been called in DataProxy
1671 if (success === true) {
1672 this.fireEvent('write', this, action, data, response, rs);
1677 // Clears records from modified array after an exception event.
1678 // NOTE: records are left marked dirty. Do we want to commit them even though they were not updated/realized?
1679 clearModified : function(rs) {
1680 if (Ext.isArray(rs)) {
1681 for (var n=rs.length-1;n>=0;n--) {
1682 this.modified.splice(this.modified.indexOf(rs[n]), 1);
1685 this.modified.splice(this.modified.indexOf(rs), 1);
1689 // remap record ids in MixedCollection after records have been realized. @see Store#onCreateRecords, @see DataReader#realize
1690 reMap : function(record) {
1691 if (Ext.isArray(record)) {
1692 for (var i = 0, len = record.length; i < len; i++) {
1693 this.reMap(record[i]);
1696 delete this.data.map[record._phid];
1697 this.data.map[record.id] = record;
1698 var index = this.data.keys.indexOf(record._phid);
1699 this.data.keys.splice(index, 1, record.id);
1700 delete record._phid;
1704 // @protected onCreateRecord proxy callback for create action
1705 onCreateRecords : function(success, rs, data) {
1706 if (success === true) {
1708 this.reader.realize(rs, data);
1712 this.handleException(e);
1713 if (Ext.isArray(rs)) {
1714 // Recurse to run back into the try {}. DataReader#realize splices-off the rs until empty.
1715 this.onCreateRecords(success, rs, data);
1721 // @protected, onUpdateRecords proxy callback for update action
1722 onUpdateRecords : function(success, rs, data) {
1723 if (success === true) {
1725 this.reader.update(rs, data);
1727 this.handleException(e);
1728 if (Ext.isArray(rs)) {
1729 // Recurse to run back into the try {}. DataReader#update splices-off the rs until empty.
1730 this.onUpdateRecords(success, rs, data);
1736 // @protected onDestroyRecords proxy callback for destroy action
1737 onDestroyRecords : function(success, rs, data) {
1738 // splice each rec out of this.removed
1739 rs = (rs instanceof Ext.data.Record) ? [rs] : rs;
1740 for (var i=0,len=rs.length;i<len;i++) {
1741 this.removed.splice(this.removed.indexOf(rs[i]), 1);
1743 if (success === false) {
1744 // put records back into store if remote destroy fails.
1745 // @TODO: Might want to let developer decide.
1746 for (i=rs.length-1;i>=0;i--) {
1747 this.insert(rs[i].lastIndex, rs[i]); // <-- lastIndex set in Store#destroyRecord
1752 // protected handleException. Possibly temporary until Ext framework has an exception-handler.
1753 handleException : function(e) {
1754 // @see core/Error.js
1759 * <p>Reloads the Record cache from the configured Proxy using the configured {@link Ext.data.Reader Reader} and
1760 * the options from the last load operation performed.</p>
1761 * <p><b>Note</b>: see the Important note in {@link #load}.</p>
1762 * @param {Object} options (optional) An <tt>Object</tt> containing {@link #load loading options} which may
1763 * override the options used in the last {@link #load} operation. See {@link #load} for details (defaults to
1764 * <tt>null</tt>, in which case the {@link #lastOptions} are used).
1766 reload : function(options){
1767 this.load(Ext.applyIf(options||{}, this.lastOptions));
1771 // Called as a callback by the Reader during a load operation.
1772 loadRecords : function(o, options, success){
1773 if(!o || success === false){
1774 if(success !== false){
1775 this.fireEvent('load', this, [], options);
1777 if(options.callback){
1778 options.callback.call(options.scope || this, [], options, false, o);
1782 var r = o.records, t = o.totalRecords || r.length;
1783 if(!options || options.add !== true){
1784 if(this.pruneModifiedRecords){
1787 for(var i = 0, len = r.length; i < len; i++){
1791 this.data = this.snapshot;
1792 delete this.snapshot;
1795 this.data.addAll(r);
1796 this.totalLength = t;
1798 this.fireEvent('datachanged', this);
1800 this.totalLength = Math.max(t, this.data.length+r.length);
1803 this.fireEvent('load', this, r, options);
1804 if(options.callback){
1805 options.callback.call(options.scope || this, r, options, true);
1810 * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
1811 * which understands the format of the data must have been configured in the constructor.
1812 * @param {Object} data The data block from which to read the Records. The format of the data expected
1813 * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
1814 * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
1815 * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
1816 * the existing cache.
1817 * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
1818 * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
1819 * new, unique ids will be added.
1821 loadData : function(o, append){
1822 var r = this.reader.readRecords(o);
1823 this.loadRecords(r, {add: append}, true);
1827 * Gets the number of cached records.
1828 * <p>If using paging, this may not be the total size of the dataset. If the data object
1829 * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1830 * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p>
1831 * @return {Number} The number of Records in the Store's cache.
1833 getCount : function(){
1834 return this.data.length || 0;
1838 * Gets the total number of records in the dataset as returned by the server.
1839 * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
1840 * must contain the dataset size. For remote data sources, the value for this property
1841 * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
1842 * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
1843 * <b>Note</b>: see the Important note in {@link #load}.</p>
1844 * @return {Number} The number of Records as specified in the data object passed to the Reader
1846 * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
1848 getTotalCount : function(){
1849 return this.totalLength || 0;
1853 * Returns an object describing the current sort state of this Store.
1854 * @return {Object} The sort state of the Store. An object with two properties:<ul>
1855 * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
1856 * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
1858 * See <tt>{@link #sortInfo}</tt> for additional details.
1860 getSortState : function(){
1861 return this.sortInfo;
1865 applySort : function(){
1866 if(this.sortInfo && !this.remoteSort){
1867 var s = this.sortInfo, f = s.field;
1868 this.sortData(f, s.direction);
1873 sortData : function(f, direction){
1874 direction = direction || 'ASC';
1875 var st = this.fields.get(f).sortType;
1876 var fn = function(r1, r2){
1877 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
1878 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
1880 this.data.sort(direction, fn);
1881 if(this.snapshot && this.snapshot != this.data){
1882 this.snapshot.sort(direction, fn);
1887 * Sets the default sort column and order to be used by the next {@link #load} operation.
1888 * @param {String} fieldName The name of the field to sort by.
1889 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1891 setDefaultSort : function(field, dir){
1892 dir = dir ? dir.toUpperCase() : 'ASC';
1893 this.sortInfo = {field: field, direction: dir};
1894 this.sortToggle[field] = dir;
1899 * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
1900 * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
1901 * @param {String} fieldName The name of the field to sort by.
1902 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1904 sort : function(fieldName, dir){
1905 var f = this.fields.get(fieldName);
1910 if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
1911 dir = (this.sortToggle[f.name] || 'ASC').toggle('ASC', 'DESC');
1916 var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
1917 var si = (this.sortInfo) ? this.sortInfo : null;
1919 this.sortToggle[f.name] = dir;
1920 this.sortInfo = {field: f.name, direction: dir};
1921 if(!this.remoteSort){
1923 this.fireEvent('datachanged', this);
1925 if (!this.load(this.lastOptions)) {
1927 this.sortToggle[f.name] = st;
1937 * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
1938 * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
1939 * Returning <tt>false</tt> aborts and exits the iteration.
1940 * @param {Object} scope (optional) The scope in which to call the function (defaults to the {@link Ext.data.Record Record}).
1942 each : function(fn, scope){
1943 this.data.each(fn, scope);
1947 * Gets all {@link Ext.data.Record records} modified since the last commit. Modified records are
1948 * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
1949 * included. See also <tt>{@link #pruneModifiedRecords}</tt> and
1950 * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
1951 * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
1952 * modifications. To obtain modified fields within a modified record see
1953 *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
1955 getModifiedRecords : function(){
1956 return this.modified;
1960 createFilterFn : function(property, value, anyMatch, caseSensitive){
1961 if(Ext.isEmpty(value, false)){
1964 value = this.data.createValueMatcher(value, anyMatch, caseSensitive);
1966 return value.test(r.data[property]);
1971 * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
1972 * and <tt>end</tt> and returns the result.
1973 * @param {String} property A field in each record
1974 * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
1975 * @param {Number} end (optional) The last record index to include (defaults to length - 1)
1976 * @return {Number} The sum
1978 sum : function(property, start, end){
1979 var rs = this.data.items, v = 0;
1981 end = (end || end === 0) ? end : rs.length-1;
1983 for(var i = start; i <= end; i++){
1984 v += (rs[i].data[property] || 0);
1990 * Filter the {@link Ext.data.Record records} by a specified property.
1991 * @param {String} field A field on your records
1992 * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
1993 * against the field.
1994 * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
1995 * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
1997 filter : function(property, value, anyMatch, caseSensitive){
1998 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1999 return fn ? this.filterBy(fn) : this.clearFilter();
2003 * Filter by a function. The specified function will be called for each
2004 * Record in this Store. If the function returns <tt>true</tt> the Record is included,
2005 * otherwise it is filtered out.
2006 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2007 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2008 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2009 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2011 * @param {Object} scope (optional) The scope of the function (defaults to this)
2013 filterBy : function(fn, scope){
2014 this.snapshot = this.snapshot || this.data;
2015 this.data = this.queryBy(fn, scope||this);
2016 this.fireEvent('datachanged', this);
2020 * Query the records by a specified property.
2021 * @param {String} field A field on your records
2022 * @param {String/RegExp} value Either a string that the field
2023 * should begin with, or a RegExp to test against the field.
2024 * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
2025 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
2026 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
2028 query : function(property, value, anyMatch, caseSensitive){
2029 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2030 return fn ? this.queryBy(fn) : this.data.clone();
2034 * Query the cached records in this Store using a filtering function. The specified function
2035 * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
2036 * included in the results.
2037 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2038 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2039 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2040 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2042 * @param {Object} scope (optional) The scope of the function (defaults to this)
2043 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
2045 queryBy : function(fn, scope){
2046 var data = this.snapshot || this.data;
2047 return data.filterBy(fn, scope||this);
2051 * Finds the index of the first matching record in this store by a specific property/value.
2052 * @param {String} property A property on your objects
2053 * @param {String/RegExp} value Either a string that the property value
2054 * should begin with, or a RegExp to test against the property.
2055 * @param {Number} startIndex (optional) The index to start searching at
2056 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
2057 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
2058 * @return {Number} The matched index or -1
2060 find : function(property, value, start, anyMatch, caseSensitive){
2061 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2062 return fn ? this.data.findIndexBy(fn, null, start) : -1;
2066 * Finds the index of the first matching record in this store by a specific property/value.
2067 * @param {String} property A property on your objects
2068 * @param {String/RegExp} value The value to match against
2069 * @param {Number} startIndex (optional) The index to start searching at
2070 * @return {Number} The matched index or -1
2072 findExact: function(property, value, start){
2073 return this.data.findIndexBy(function(rec){
2074 return rec.get(property) === value;
2079 * Find the index of the first matching Record in this Store by a function.
2080 * If the function returns <tt>true</tt> it is considered a match.
2081 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2082 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2083 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2084 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2086 * @param {Object} scope (optional) The scope of the function (defaults to this)
2087 * @param {Number} startIndex (optional) The index to start searching at
2088 * @return {Number} The matched index or -1
2090 findBy : function(fn, scope, start){
2091 return this.data.findIndexBy(fn, scope, start);
2095 * Collects unique values for a particular dataIndex from this store.
2096 * @param {String} dataIndex The property to collect
2097 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
2098 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
2099 * @return {Array} An array of the unique values
2101 collect : function(dataIndex, allowNull, bypassFilter){
2102 var d = (bypassFilter === true && this.snapshot) ?
2103 this.snapshot.items : this.data.items;
2104 var v, sv, r = [], l = {};
2105 for(var i = 0, len = d.length; i < len; i++){
2106 v = d[i].data[dataIndex];
2108 if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
2117 * Revert to a view of the Record cache with no filtering applied.
2118 * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
2119 * {@link #datachanged} event.
2121 clearFilter : function(suppressEvent){
2122 if(this.isFiltered()){
2123 this.data = this.snapshot;
2124 delete this.snapshot;
2125 if(suppressEvent !== true){
2126 this.fireEvent('datachanged', this);
2132 * Returns true if this store is currently filtered
2135 isFiltered : function(){
2136 return this.snapshot && this.snapshot != this.data;
2140 afterEdit : function(record){
2141 if(this.modified.indexOf(record) == -1){
2142 this.modified.push(record);
2144 this.fireEvent('update', this, record, Ext.data.Record.EDIT);
2148 afterReject : function(record){
2149 this.modified.remove(record);
2150 this.fireEvent('update', this, record, Ext.data.Record.REJECT);
2154 afterCommit : function(record){
2155 this.modified.remove(record);
2156 this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
2160 * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
2161 * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
2162 * Ext.data.Record.COMMIT.
2164 commitChanges : function(){
2165 var m = this.modified.slice(0);
2167 for(var i = 0, len = m.length; i < len; i++){
2173 * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
2175 rejectChanges : function(){
2176 var m = this.modified.slice(0);
2178 for(var i = 0, len = m.length; i < len; i++){
2184 onMetaChange : function(meta, rtype, o){
2185 this.recordType = rtype;
2186 this.fields = rtype.prototype.fields;
2187 delete this.snapshot;
2189 this.sortInfo = meta.sortInfo;
2190 }else if(this.sortInfo && !this.fields.get(this.sortInfo.field)){
2191 delete this.sortInfo;
2194 this.fireEvent('metachange', this, this.reader.meta);
2198 findInsertIndex : function(record){
2199 this.suspendEvents();
2200 var data = this.data.clone();
2201 this.data.add(record);
2203 var index = this.data.indexOf(record);
2205 this.resumeEvents();
2210 * Set the value for a property name in this store's {@link #baseParams}. Usage:</p><pre><code>
2211 myStore.setBaseParam('foo', {bar:3});
2213 * @param {String} name Name of the property to assign
2214 * @param {Mixed} value Value to assign the <tt>name</tt>d property
2216 setBaseParam : function (name, value){
2217 this.baseParams = this.baseParams || {};
2218 this.baseParams[name] = value;
2222 Ext.reg('store', Ext.data.Store);
2225 * @class Ext.data.Store.Error
2226 * @extends Ext.Error
2227 * Store Error extension.
2228 * @param {String} name
2230 Ext.data.Store.Error = Ext.extend(Ext.Error, {
2231 name: 'Ext.data.Store'
2233 Ext.apply(Ext.data.Store.Error.prototype, {
2235 'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'
2240 * @class Ext.data.Field
2241 * <p>This class encapsulates the field definition information specified in the field definition objects
2242 * passed to {@link Ext.data.Record#create}.</p>
2243 * <p>Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
2244 * and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
2246 Ext.data.Field = function(config){
2247 if(typeof config == "string"){
2248 config = {name: config};
2250 Ext.apply(this, config);
2256 var st = Ext.data.SortTypes;
2257 // named sortTypes are supported, here we look them up
2258 if(typeof this.sortType == "string"){
2259 this.sortType = st[this.sortType];
2262 // set default sortType for strings and dates
2266 this.sortType = st.asUCString;
2269 this.sortType = st.asDate;
2272 this.sortType = st.none;
2277 var stripRe = /[\$,%]/g;
2279 // prebuilt conversion function for this field, instead of
2280 // switching every time we're reading a value
2282 var cv, dateFormat = this.dateFormat;
2287 cv = function(v){ return v; };
2290 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
2294 return v !== undefined && v !== null && v !== '' ?
2295 parseInt(String(v).replace(stripRe, ""), 10) : '';
2300 return v !== undefined && v !== null && v !== '' ?
2301 parseFloat(String(v).replace(stripRe, ""), 10) : '';
2306 cv = function(v){ return v === true || v === "true" || v == 1; };
2317 if(dateFormat == "timestamp"){
2318 return new Date(v*1000);
2320 if(dateFormat == "time"){
2321 return new Date(parseInt(v, 10));
2323 return Date.parseDate(v, dateFormat);
2325 var parsed = Date.parse(v);
2326 return parsed ? new Date(parsed) : null;
2335 Ext.data.Field.prototype = {
2337 * @cfg {String} name
2338 * The name by which the field is referenced within the Record. This is referenced by, for example,
2339 * the <tt>dataIndex</tt> property in column definition objects passed to {@link Ext.grid.ColumnModel}.
2340 * <p>Note: In the simplest case, if no properties other than <tt>name</tt> are required, a field
2341 * definition may consist of just a String for the field name.</p>
2344 * @cfg {String} type
2345 * (Optional) The data type for conversion to displayable value if <tt>{@link Ext.data.Field#convert convert}</tt>
2346 * has not been specified. Possible values are
2347 * <div class="mdetail-params"><ul>
2348 * <li>auto (Default, implies no conversion)</li>
2353 * <li>date</li></ul></div>
2356 * @cfg {Function} convert
2357 * (Optional) A function which converts the value provided by the Reader into an object that will be stored
2358 * in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
2359 * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
2360 * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
2361 * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
2362 * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
2363 * ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
2366 // example of convert function
2367 function fullName(v, record){
2368 return record.name.last + ', ' + record.name.first;
2371 function location(v, record){
2372 return !record.city ? '' : (record.city + ', ' + record.state);
2375 var Dude = Ext.data.Record.create([
2376 {name: 'fullname', convert: fullName},
2377 {name: 'firstname', mapping: 'name.first'},
2378 {name: 'lastname', mapping: 'name.last'},
2379 {name: 'city', defaultValue: 'homeless'},
2381 {name: 'location', convert: location}
2384 // create the data store
2385 var store = new Ext.data.Store({
2386 reader: new Ext.data.JsonReader(
2390 totalProperty: 'total'
2398 name: { first: 'Fat', last: 'Albert' }
2399 // notice no city, state provided in data object
2402 name: { first: 'Barney', last: 'Rubble' },
2403 city: 'Bedrock', state: 'Stoneridge'
2406 name: { first: 'Cliff', last: 'Claven' },
2407 city: 'Boston', state: 'MA'
2413 * @cfg {String} dateFormat
2414 * (Optional) A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
2415 * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
2416 * javascript millisecond timestamp.
2420 * @cfg {Mixed} defaultValue
2421 * (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b>
2422 * when the item referenced by the <tt>{@link Ext.data.Field#mapping mapping}</tt> does not exist in the data
2423 * object (i.e. undefined). (defaults to "")
2427 * @cfg {String/Number} mapping
2428 * <p>(Optional) A path expression for use by the {@link Ext.data.DataReader} implementation
2429 * that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object.
2430 * If the path expression is the same as the field name, the mapping may be omitted.</p>
2431 * <p>The form of the mapping expression depends on the Reader being used.</p>
2432 * <div class="mdetail-params"><ul>
2433 * <li>{@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript
2434 * expression to reference the data from an element of the data item's {@link Ext.data.JsonReader#root root} Array. Defaults to the field name.</div></li>
2435 * <li>{@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
2436 * item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li>
2437 * <li>{@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index
2438 * of the field's value. Defaults to the field specification's Array position.</div></li>
2440 * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
2441 * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
2442 * return the desired data.</p>
2446 * @cfg {Function} sortType
2447 * (Optional) A function which converts a Field's value to a comparable value in order to ensure
2448 * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
2449 * sort example:<pre><code>
2450 // current sort after sort we want
2451 // +-+------+ +-+------+
2452 // |1|First | |1|First |
2453 // |2|Last | |3|Second|
2454 // |3|Second| |2|Last |
2455 // +-+------+ +-+------+
2457 sortType: function(value) {
2458 switch (value.toLowerCase()) // native toLowerCase():
2460 case 'first': return 1;
2461 case 'second': return 2;
2469 * @cfg {String} sortDir
2470 * (Optional) Initial direction to sort (<tt>"ASC"</tt> or <tt>"DESC"</tt>). Defaults to
2475 * @cfg {Boolean} allowBlank
2476 * (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <tt>true</tt>.
2477 * An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}
2478 * to evaluate to <tt>false</tt>.
2482 * @class Ext.data.DataReader
\r
2483 * Abstract base class for reading structured data from a data source and converting
\r
2484 * it into an object containing {@link Ext.data.Record} objects and metadata for use
\r
2485 * by an {@link Ext.data.Store}. This class is intended to be extended and should not
\r
2486 * be created directly. For existing implementations, see {@link Ext.data.ArrayReader},
\r
2487 * {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.
\r
2488 * @constructor Create a new DataReader
\r
2489 * @param {Object} meta Metadata configuration options (implementation-specific).
\r
2490 * @param {Array/Object} recordType
\r
2491 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
\r
2492 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
\r
2493 * constructor created using {@link Ext.data.Record#create}.</p>
\r
2495 Ext.data.DataReader = function(meta, recordType){
\r
2497 * This DataReader's configured metadata as passed to the constructor.
\r
2503 * @cfg {Array/Object} fields
\r
2504 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
\r
2505 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
\r
2506 * constructor created from {@link Ext.data.Record#create}.</p>
\r
2508 this.recordType = Ext.isArray(recordType) ?
\r
2509 Ext.data.Record.create(recordType) : recordType;
\r
2512 Ext.data.DataReader.prototype = {
\r
2515 * Abstract method, overridden in {@link Ext.data.JsonReader}
\r
2517 buildExtractors : Ext.emptyFn,
\r
2520 * Used for un-phantoming a record after a successful database insert. Sets the records pk along with new data from server.
\r
2521 * You <b>must</b> return at least the database pk using the idProperty defined in your DataReader configuration. The incoming
\r
2522 * data from server will be merged with the data in the local record.
\r
2523 * In addition, you <b>must</b> return record-data from the server in the same order received.
\r
2524 * Will perform a commit as well, un-marking dirty-fields. Store's "update" event will be suppressed.
\r
2525 * @param {Record/Record[]} record The phantom record to be realized.
\r
2526 * @param {Object/Object[]} data The new record data to apply. Must include the primary-key from database defined in idProperty field.
\r
2528 realize: function(rs, data){
\r
2529 if (Ext.isArray(rs)) {
\r
2530 for (var i = rs.length - 1; i >= 0; i--) {
\r
2532 if (Ext.isArray(data)) {
\r
2533 this.realize(rs.splice(i,1).shift(), data.splice(i,1).shift());
\r
2536 // weird...rs is an array but data isn't?? recurse but just send in the whole invalid data object.
\r
2537 // the else clause below will detect !this.isData and throw exception.
\r
2538 this.realize(rs.splice(i,1).shift(), data);
\r
2543 // If rs is NOT an array but data IS, see if data contains just 1 record. If so extract it and carry on.
\r
2544 if (Ext.isArray(data) && data.length == 1) {
\r
2545 data = data.shift();
\r
2547 if (!this.isData(data)) {
\r
2548 // TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.
\r
2550 throw new Ext.data.DataReader.Error('realize', rs);
\r
2552 this.buildExtractors();
\r
2553 var values = this.extractValues(data, rs.fields.items, rs.fields.items.length);
\r
2554 rs.phantom = false; // <-- That's what it's all about
\r
2555 rs._phid = rs.id; // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords
\r
2556 rs.id = data[this.meta.idProperty];
\r
2563 * Used for updating a non-phantom or "real" record's data with fresh data from server after remote-save.
\r
2564 * You <b>must</b> return a complete new record from the server. If you don't, your local record's missing fields
\r
2565 * will be populated with the default values specified in your Ext.data.Record.create specification. Without a defaultValue,
\r
2566 * local fields will be populated with empty string "". So return your entire record's data after both remote create and update.
\r
2567 * In addition, you <b>must</b> return record-data from the server in the same order received.
\r
2568 * Will perform a commit as well, un-marking dirty-fields. Store's "update" event will be suppressed as the record receives
\r
2569 * a fresh new data-hash.
\r
2570 * @param {Record/Record[]} rs
\r
2571 * @param {Object/Object[]} data
\r
2573 update : function(rs, data) {
\r
2574 if (Ext.isArray(rs)) {
\r
2575 for (var i=rs.length-1; i >= 0; i--) {
\r
2576 if (Ext.isArray(data)) {
\r
2577 this.update(rs.splice(i,1).shift(), data.splice(i,1).shift());
\r
2580 // weird...rs is an array but data isn't?? recurse but just send in the whole data object.
\r
2581 // the else clause below will detect !this.isData and throw exception.
\r
2582 this.update(rs.splice(i,1).shift(), data);
\r
2587 // If rs is NOT an array but data IS, see if data contains just 1 record. If so extract it and carry on.
\r
2588 if (Ext.isArray(data) && data.length == 1) {
\r
2589 data = data.shift();
\r
2591 if (!this.isData(data)) {
\r
2592 // TODO: create custom Exception class to return record in thrown exception. Allow exception-handler the choice
\r
2593 // to commit or not rather than blindly rs.commit() here.
\r
2595 throw new Ext.data.DataReader.Error('update', rs);
\r
2597 this.buildExtractors();
\r
2598 rs.data = this.extractValues(Ext.apply(rs.data, data), rs.fields.items, rs.fields.items.length);
\r
2604 * Returns true if the supplied data-hash <b>looks</b> and quacks like data. Checks to see if it has a key
\r
2605 * corresponding to idProperty defined in your DataReader config containing non-empty pk.
\r
2606 * @param {Object} data
\r
2607 * @return {Boolean}
\r
2609 isData : function(data) {
\r
2610 return (data && Ext.isObject(data) && !Ext.isEmpty(data[this.meta.idProperty])) ? true : false;
\r
2615 * @class Ext.data.DataReader.Error
\r
2616 * @extends Ext.Error
\r
2617 * General error class for Ext.data.DataReader
\r
2619 Ext.data.DataReader.Error = Ext.extend(Ext.Error, {
\r
2620 constructor : function(message, arg) {
\r
2622 Ext.Error.call(this, message);
\r
2624 name: 'Ext.data.DataReader'
\r
2626 Ext.apply(Ext.data.DataReader.Error.prototype, {
\r
2628 'update': "#update received invalid data from server. Please see docs for DataReader#update and review your DataReader configuration.",
\r
2629 'realize': "#realize was called with invalid remote-data. Please see the docs for DataReader#realize and review your DataReader configuration.",
\r
2630 'invalid-response': "#readResponse received an invalid response from the server."
\r
2636 * @class Ext.data.DataWriter
2637 * <p>Ext.data.DataWriter facilitates create, update, and destroy actions between
2638 * an Ext.data.Store and a server-side framework. A Writer enabled Store will
2639 * automatically manage the Ajax requests to perform CRUD actions on a Store.</p>
2640 * <p>Ext.data.DataWriter is an abstract base class which is intended to be extended
2641 * and should not be created directly. For existing implementations, see
2642 * {@link Ext.data.JsonWriter}.</p>
2643 * <p>Creating a writer is simple:</p>
2645 var writer = new Ext.data.JsonWriter();
2647 * <p>The proxy for a writer enabled store can be configured with a simple <code>url</code>:</p>
2649 // Create a standard HttpProxy instance.
2650 var proxy = new Ext.data.HttpProxy({
2651 url: 'app.php/users'
2654 * <p>For finer grained control, the proxy may also be configured with an <code>api</code>:</p>
2656 // Use the api specification
2657 var proxy = new Ext.data.HttpProxy({
2659 read : 'app.php/users/read',
2660 create : 'app.php/users/create',
2661 update : 'app.php/users/update',
2662 destroy : 'app.php/users/destroy'
2666 * <p>Creating a Writer enabled store:</p>
2668 var store = new Ext.data.Store({
2674 * @constructor Create a new DataWriter
2675 * @param {Object} meta Metadata configuration options (implementation-specific)
2676 * @param {Object} recordType Either an Array of field definition objects as specified
2677 * in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
2678 * using {@link Ext.data.Record#create}.
2680 Ext.data.DataWriter = function(config){
2682 * This DataWriter's configured metadata as passed to the constructor.
2686 Ext.apply(this, config);
2689 Ext.data.DataWriter.prototype = {
2692 * @cfg {Boolean} writeAllFields
2693 * <tt>false</tt> by default. Set <tt>true</tt> to have DataWriter return ALL fields of a modified
2694 * record -- not just those that changed.
2695 * <tt>false</tt> to have DataWriter only request modified fields from a record.
2697 writeAllFields : false,
2699 * @cfg {Boolean} listful
2700 * <tt>false</tt> by default. Set <tt>true</tt> to have the DataWriter <b>always</b> write HTTP params as a list,
2701 * even when acting upon a single record.
2703 listful : false, // <-- listful is actually not used internally here in DataWriter. @see Ext.data.Store#execute.
2706 * Writes data in preparation for server-write action. Simply proxies to DataWriter#update, DataWriter#create
2707 * DataWriter#destroy.
2708 * @param {String} action [CREATE|UPDATE|DESTROY]
2709 * @param {Object} params The params-hash to write-to
2710 * @param {Record/Record[]} rs The recordset write.
2712 write : function(action, params, rs) {
2713 this.render(action, rs, params, this[action](rs));
2717 * abstract method meant to be overridden by all DataWriter extensions. It's the extension's job to apply the "data" to the "params".
2718 * The data-object provided to render is populated with data according to the meta-info defined in the user's DataReader config,
2719 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
2720 * @param {Record[]} rs Store recordset
2721 * @param {Object} params Http params to be sent to server.
2722 * @param {Object} data object populated according to DataReader meta-data.
2724 render : Ext.emptyFn,
2728 * @param {Object} p Params-hash to apply result to.
2729 * @param {Record/Record[]} rs Record(s) to write
2732 update : function(rs) {
2734 if (Ext.isArray(rs)) {
2737 Ext.each(rs, function(val){
2739 data.push(this.updateRecord(val));
2741 params[this.meta.idProperty] = ids;
2742 params[this.meta.root] = data;
2744 else if (rs instanceof Ext.data.Record) {
2745 params[this.meta.idProperty] = rs.id;
2746 params[this.meta.root] = this.updateRecord(rs);
2752 * @cfg {Function} saveRecord Abstract method that should be implemented in all subclasses
2753 * (e.g.: {@link Ext.data.JsonWriter#saveRecord JsonWriter.saveRecord}
2755 updateRecord : Ext.emptyFn,
2759 * @param {Object} p Params-hash to apply result to.
2760 * @param {Record/Record[]} rs Record(s) to write
2763 create : function(rs) {
2765 if (Ext.isArray(rs)) {
2767 Ext.each(rs, function(val){
2768 data.push(this.createRecord(val));
2770 params[this.meta.root] = data;
2772 else if (rs instanceof Ext.data.Record) {
2773 params[this.meta.root] = this.createRecord(rs);
2779 * @cfg {Function} createRecord Abstract method that should be implemented in all subclasses
2780 * (e.g.: {@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord})
2782 createRecord : Ext.emptyFn,
2786 * @param {Object} p Params-hash to apply result to.
2787 * @param {Record/Record[]} rs Record(s) to write
2790 destroy : function(rs) {
2792 if (Ext.isArray(rs)) {
2795 Ext.each(rs, function(val){
2796 data.push(this.destroyRecord(val));
2798 params[this.meta.root] = data;
2799 } else if (rs instanceof Ext.data.Record) {
2800 params[this.meta.root] = this.destroyRecord(rs);
2806 * @cfg {Function} destroyRecord Abstract method that should be implemented in all subclasses
2807 * (e.g.: {@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord})
2809 destroyRecord : Ext.emptyFn,
2812 * Converts a Record to a hash
2816 toHash : function(rec) {
2817 var map = rec.fields.map,
2819 raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
2821 Ext.iterate(raw, function(prop, value){
2822 if((m = map[prop])){
2823 data[m.mapping ? m.mapping : m.name] = value;
2826 data[this.meta.idProperty] = rec.id;
2830 * @class Ext.data.DataProxy
\r
2831 * @extends Ext.util.Observable
\r
2832 * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.
\r
2833 * This class is intended to be extended and should not be created directly. For existing implementations,
\r
2834 * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and
\r
2835 * {@link Ext.data.MemoryProxy}.</p>
\r
2836 * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}
\r
2837 * (of the appropriate type which knows how to parse the data object) to provide a block of
\r
2838 * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>
\r
2839 * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the
\r
2840 * config object to an {@link Ext.data.Connection}.</p>
\r
2841 * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the
\r
2842 * <code>load</code> method (deprecated). See
\r
2843 * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or
\r
2844 * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>
\r
2845 * <p><b><u>Example 1</u></b></p>
\r
2847 proxy: new Ext.data.ScriptTagProxy({
\r
2848 {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'
\r
2851 * <p><b><u>Example 2</u></b></p>
\r
2853 proxy : new Ext.data.HttpProxy({
\r
2854 {@link Ext.data.Connection#method method}: 'GET',
\r
2855 {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,
\r
2856 {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}
\r
2858 // all actions except the following will use above url
\r
2859 create : 'local/new.php',
\r
2860 update : 'local/update.php'
\r
2865 Ext.data.DataProxy = function(conn){
\r
2866 // make sure we have a config object here to support ux proxies.
\r
2867 // All proxies should now send config into superclass constructor.
\r
2868 conn = conn || {};
\r
2870 // This line caused a bug when people use custom Connection object having its own request method.
\r
2871 // http://extjs.com/forum/showthread.php?t=67194. Have to set DataProxy config
\r
2872 //Ext.applyIf(this, conn);
\r
2874 this.api = conn.api;
\r
2875 this.url = conn.url;
\r
2876 this.restful = conn.restful;
\r
2877 this.listeners = conn.listeners;
\r
2880 this.prettyUrls = conn.prettyUrls;
\r
2883 * @cfg {Object} api
\r
2884 * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".
\r
2885 * Defaults to:<pre><code>
\r
2888 create : undefined,
\r
2889 update : undefined,
\r
2890 destroy : undefined
\r
2893 * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request
\r
2894 * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>
\r
2895 * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API
\r
2896 * property should be modified before the action is requested using the corresponding before
\r
2897 * action event. For example to modify the URL associated with the load action:
\r
2899 // modify the url for the action
\r
2902 fn: function (store, options) {
\r
2903 // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.
\r
2904 store.proxy.setUrl('changed1.php');
\r
2906 // set optional second parameter to true to make this URL change
\r
2907 // permanent, applying this URL for all subsequent requests.
\r
2908 store.proxy.setUrl('changed1.php', true);
\r
2910 // manually set the <b>private</b> connection URL.
\r
2911 // <b>Warning:</b> Accessing the private URL property should be avoided.
\r
2912 // Use the public method <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> instead, shown above.
\r
2913 // It should be noted that changing the URL like this will affect
\r
2914 // the URL for just this request. Subsequent requests will use the
\r
2915 // API or URL defined in your initial proxy configuration.
\r
2916 store.proxy.conn.url = 'changed1.php';
\r
2918 // proxy URL will be superseded by API (only if proxy created to use ajax):
\r
2919 // It should be noted that proxy API changes are permanent and will
\r
2920 // be used for all subsequent requests.
\r
2921 store.proxy.api.load = 'changed2.php';
\r
2923 // However, altering the proxy API should be done using the public
\r
2924 // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt> instead.
\r
2925 store.proxy.setApi('load', 'changed2.php');
\r
2927 // Or set the entire API with a config-object.
\r
2928 // When using the config-object option, you must redefine the <b>entire</b>
\r
2929 // API -- not just a specific action of it.
\r
2930 store.proxy.setApi({
\r
2931 read : 'changed_read.php',
\r
2932 create : 'changed_create.php',
\r
2933 update : 'changed_update.php',
\r
2934 destroy : 'changed_destroy.php'
\r
2942 // Prepare the proxy api. Ensures all API-actions are defined with the Object-form.
\r
2944 Ext.data.Api.prepare(this);
\r
2946 if (e instanceof Ext.data.Api.Error) {
\r
2953 * @event exception
\r
2954 * <p>Fires if an exception occurs in the Proxy during a remote request.
\r
2955 * This event is relayed through a corresponding
\r
2956 * {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},
\r
2957 * so any Store instance may observe this event.
\r
2958 * This event can be fired for one of two reasons:</p>
\r
2959 * <div class="mdetail-params"><ul>
\r
2960 * <li>remote-request <b>failed</b> : <div class="sub-desc">
\r
2961 * The server did not return status === 200.
\r
2963 * <li>remote-request <b>succeeded</b> : <div class="sub-desc">
\r
2964 * The remote-request succeeded but the reader could not read the response.
\r
2965 * This means the server returned data, but the configured Reader threw an
\r
2966 * error while reading the response. In this case, this event will be
\r
2967 * raised and the caught error will be passed along into this event.
\r
2970 * <br><p>This event fires with two different contexts based upon the 2nd
\r
2971 * parameter <tt>type [remote|response]</tt>. The first four parameters
\r
2972 * are identical between the two contexts -- only the final two parameters
\r
2974 * @param {DataProxy} this The proxy that sent the request
\r
2975 * @param {String} type
\r
2976 * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>
\r
2977 * <div class="mdetail-params"><ul>
\r
2978 * <li><b><tt>'response'</tt></b> : <div class="sub-desc">
\r
2979 * <p>An <b>invalid</b> response from the server was returned: either 404,
\r
2980 * 500 or the response meta-data does not match that defined in the DataReader
\r
2981 * (e.g.: root, idProperty, successProperty).</p>
\r
2983 * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
\r
2984 * <p>A <b>valid</b> response was returned from the server having
\r
2985 * successProperty === false. This response might contain an error-message
\r
2986 * sent from the server. For example, the user may have failed
\r
2987 * authentication/authorization or a database validation error occurred.</p>
\r
2990 * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.
\r
2991 * @param {Object} options The options for the action that were specified in the {@link #request}.
\r
2992 * @param {Object} response
\r
2993 * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>
\r
2994 * <div class="mdetail-params"><ul>
\r
2995 * <li><b><tt>'response'</tt></b> : <div class="sub-desc">
\r
2996 * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>
\r
2998 * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
\r
2999 * <p>The decoded response object sent from the server.</p>
\r
3002 * @param {Mixed} arg
\r
3003 * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>
\r
3004 * <div class="mdetail-params"><ul>
\r
3005 * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">
\r
3006 * <p>The JavaScript Error object caught if the configured Reader could not read the data.
\r
3007 * If the remote request returns success===false, this parameter will be null.</p>
\r
3009 * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">
\r
3010 * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action
\r
3011 * (Ext.data.Api.actions.create|update|destroy).</p>
\r
3017 * @event beforeload
\r
3018 * Fires before a request to retrieve a data object.
\r
3019 * @param {DataProxy} this The proxy for the request
\r
3020 * @param {Object} params The params object passed to the {@link #request} function
\r
3025 * Fires before the load method's callback is called.
\r
3026 * @param {DataProxy} this The proxy for the request
\r
3027 * @param {Object} o The request transaction object
\r
3028 * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
\r
3032 * @event loadexception
\r
3033 * <p>This event is <b>deprecated</b>. The signature of the loadexception event
\r
3034 * varies depending on the proxy, use the catch-all {@link #exception} event instead.
\r
3035 * This event will fire in addition to the {@link #exception} event.</p>
\r
3036 * @param {misc} misc See {@link #exception}.
\r
3041 * @event beforewrite
\r
3042 * Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy
\r
3043 * @param {DataProxy} this The proxy for the request
\r
3044 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
\r
3045 * @param {Record/Array[Record]} rs The Record(s) to create|update|destroy.
\r
3046 * @param {Object} params The request <code>params</code> object. Edit <code>params</code> to add parameters to the request.
\r
3051 * Fires before the request-callback is called
\r
3052 * @param {DataProxy} this The proxy that sent the request
\r
3053 * @param {String} action [Ext.data.Api.actions.create|upate|destroy]
\r
3054 * @param {Object} data The data object extracted from the server-response
\r
3055 * @param {Object} response The decoded response from server
\r
3056 * @param {Record/Record{}} rs The records from Store
\r
3057 * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
\r
3061 Ext.data.DataProxy.superclass.constructor.call(this);
\r
3064 Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {
\r
3066 * @cfg {Boolean} restful
\r
3067 * <p>Defaults to <tt>false</tt>. Set to <tt>true</tt> to operate in a RESTful manner.</p>
\r
3068 * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the
\r
3069 * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the
\r
3070 * Store is RESTful, there is no need to set this option on the proxy.</p>
\r
3071 * <br><p>RESTful implementations enable the serverside framework to automatically route
\r
3072 * actions sent to one url based upon the HTTP method, for example:
\r
3074 store: new Ext.data.Store({
\r
3076 proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users
\r
3080 * There is no <code>{@link #api}</code> specified in the configuration of the proxy,
\r
3081 * all requests will be marshalled to a single RESTful url (/users) so the serverside
\r
3082 * framework can inspect the HTTP Method and act accordingly:
\r
3084 <u>Method</u> <u>url</u> <u>action</u>
\r
3085 POST /users create
\r
3087 PUT /users/23 update
\r
3088 DESTROY /users/23 delete
\r
3094 * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>
\r
3095 * <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>
\r
3097 read : '/users/read',
\r
3098 create : '/users/create',
\r
3099 update : '/users/update',
\r
3100 destroy : '/users/destroy'
\r
3103 * <p>If called with two parameters, the first parameter should be a string specifying the API action to
\r
3104 * redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>
\r
3105 proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');
\r
3107 * @param {String/Object} api An API specification object, or the name of an action.
\r
3108 * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.
\r
3110 setApi : function() {
\r
3111 if (arguments.length == 1) {
\r
3112 var valid = Ext.data.Api.isValid(arguments[0]);
\r
3113 if (valid === true) {
\r
3114 this.api = arguments[0];
\r
3117 throw new Ext.data.Api.Error('invalid', valid);
\r
3120 else if (arguments.length == 2) {
\r
3121 if (!Ext.data.Api.isAction(arguments[0])) {
\r
3122 throw new Ext.data.Api.Error('invalid', arguments[0]);
\r
3124 this.api[arguments[0]] = arguments[1];
\r
3126 Ext.data.Api.prepare(this);
\r
3130 * Returns true if the specified action is defined as a unique action in the api-config.
\r
3131 * request. If all API-actions are routed to unique urls, the xaction parameter is unecessary. However, if no api is defined
\r
3132 * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to
\r
3133 * the corresponding code for CRUD action.
\r
3134 * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action
\r
3135 * @return {Boolean}
\r
3137 isApiAction : function(action) {
\r
3138 return (this.api[action]) ? true : false;
\r
3142 * All proxy actions are executed through this method. Automatically fires the "before" + action event
\r
3143 * @param {String} action Name of the action
\r
3144 * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'
\r
3145 * @param {Object} params
\r
3146 * @param {Ext.data.DataReader} reader
\r
3147 * @param {Function} callback
\r
3148 * @param {Object} scope Scope with which to call the callback (defaults to the Proxy object)
\r
3149 * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.
\r
3151 request : function(action, rs, params, reader, callback, scope, options) {
\r
3152 if (!this.api[action] && !this.load) {
\r
3153 throw new Ext.data.DataProxy.Error('action-undefined', action);
\r
3155 params = params || {};
\r
3156 if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {
\r
3157 this.doRequest.apply(this, arguments);
\r
3160 callback.call(scope || this, null, options, false);
\r
3166 * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.
\r
3168 * @param {Object} params
\r
3169 * @param {Object} reader
\r
3170 * @param {Object} callback
\r
3171 * @param {Object} scope
\r
3172 * @param {Object} arg
\r
3177 * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses
\r
3178 * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},
\r
3179 * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).
\r
3181 doRequest : function(action, rs, params, reader, callback, scope, options) {
\r
3182 // default implementation of doRequest for backwards compatibility with 2.0 proxies.
\r
3183 // If we're executing here, the action is probably "load".
\r
3184 // Call with the pre-3.0 method signature.
\r
3185 this.load(params, reader, callback, scope, options);
\r
3190 * Sets the appropriate url based upon the action being executed. If restful is true, and only a single record is being acted upon,
\r
3191 * url will be built Rails-style, as in "/controller/action/32". restful will aply iff the supplied record is an
\r
3192 * instance of Ext.data.Record rather than an Array of them.
\r
3193 * @param {String} action The api action being executed [read|create|update|destroy]
\r
3194 * @param {Ext.data.Record/Array[Ext.data.Record]} The record or Array of Records being acted upon.
\r
3195 * @return {String} url
\r
3198 buildUrl : function(action, record) {
\r
3199 record = record || null;
\r
3200 var url = (this.api[action]) ? this.api[action].url : this.url;
\r
3202 throw new Ext.data.Api.Error('invalid-url', action);
\r
3205 var format = null;
\r
3206 var m = url.match(/(.*)(\.\w+)$/); // <-- look for urls with "provides" suffix, e.g.: /users.json, /users.xml, etc
\r
3211 // prettyUrls is deprectated in favor of restful-config
\r
3212 if ((this.prettyUrls === true || this.restful === true) && record instanceof Ext.data.Record && !record.phantom) {
\r
3213 url += '/' + record.id;
\r
3215 if (format) { // <-- append the request format if exists (ie: /users/update/69[.json])
\r
3222 * Destroys the proxy by purging any event listeners and cancelling any active requests.
\r
3224 destroy: function(){
\r
3225 this.purgeListeners();
\r
3230 * @class Ext.data.DataProxy.Error
\r
3231 * @extends Ext.Error
\r
3232 * DataProxy Error extension.
\r
3234 * @param {String} name
\r
3235 * @param {Record/Array[Record]/Array}
\r
3237 Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {
\r
3238 constructor : function(message, arg) {
\r
3240 Ext.Error.call(this, message);
\r
3242 name: 'Ext.data.DataProxy'
\r
3244 Ext.apply(Ext.data.DataProxy.Error.prototype, {
\r
3246 'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function. Please review your Proxy url/api-configuration.",
\r
3247 'api-invalid': 'Recieved an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'
\r
3251 * @class Ext.data.ScriptTagProxy
\r
3252 * @extends Ext.data.DataProxy
\r
3253 * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain
\r
3254 * other than the originating domain of the running page.<br>
\r
3256 * <b>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
\r
3257 * of the running page, you must use this class, rather than HttpProxy.</b><br>
\r
3259 * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript
\r
3260 * source code because it is used as the source inside a <script> tag.<br>
\r
3262 * In order for the browser to process the returned data, the server must wrap the data object
\r
3263 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
\r
3264 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
\r
3265 * depending on whether the callback name was passed:
\r
3268 boolean scriptTag = false;
\r
3269 String cb = request.getParameter("callback");
\r
3272 response.setContentType("text/javascript");
\r
3274 response.setContentType("application/x-json");
\r
3276 Writer out = response.getWriter();
\r
3278 out.write(cb + "(");
\r
3280 out.print(dataBlock.toJsonString());
\r
3287 * @param {Object} config A configuration object.
\r
3289 Ext.data.ScriptTagProxy = function(config){
\r
3290 Ext.apply(this, config);
\r
3292 Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);
\r
3294 this.head = document.getElementsByTagName("head")[0];
\r
3297 * @event loadexception
\r
3298 * <b>Deprecated</b> in favor of 'exception' event.
\r
3299 * Fires if an exception occurs in the Proxy during data loading. This event can be fired for one of two reasons:
\r
3300 * <ul><li><b>The load call timed out.</b> This means the load callback did not execute within the time limit
\r
3301 * specified by {@link #timeout}. In this case, this event will be raised and the
\r
3302 * fourth parameter (read error) will be null.</li>
\r
3303 * <li><b>The load succeeded but the reader could not read the response.</b> This means the server returned
\r
3304 * data, but the configured Reader threw an error while reading the data. In this case, this event will be
\r
3305 * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>
\r
3306 * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly
\r
3307 * on any Store instance.
\r
3308 * @param {Object} this
\r
3309 * @param {Object} options The loading options that were specified (see {@link #load} for details). If the load
\r
3310 * call timed out, this parameter will be null.
\r
3311 * @param {Object} arg The callback's arg object passed to the {@link #load} function
\r
3312 * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.
\r
3313 * If the remote request returns success: false, this parameter will be null.
\r
3317 Ext.data.ScriptTagProxy.TRANS_ID = 1000;
\r
3319 Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
\r
3321 * @cfg {String} url The URL from which to request the data object.
\r
3324 * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
\r
3328 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
\r
3329 * the server the name of the callback function set up by the load call to process the returned data object.
\r
3330 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
\r
3331 * javascript output which calls this named function passing the data object as its only parameter.
\r
3333 callbackParam : "callback",
\r
3335 * @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter
\r
3336 * name to the request.
\r
3341 * HttpProxy implementation of DataProxy#doRequest
\r
3342 * @param {String} action
\r
3343 * @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null
\r
3344 * @param {Object} params An object containing properties which are to be used as HTTP parameters
\r
3345 * for the request to the remote server.
\r
3346 * @param {Ext.data.DataReader} reader The Reader object which converts the data
\r
3347 * object into a block of Ext.data.Records.
\r
3348 * @param {Function} callback The function into which to pass the block of Ext.data.Records.
\r
3349 * The function must be passed <ul>
\r
3350 * <li>The Record block object</li>
\r
3351 * <li>The "arg" argument from the load function</li>
\r
3352 * <li>A boolean success indicator</li>
\r
3354 * @param {Object} scope The scope in which to call the callback
\r
3355 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
\r
3357 doRequest : function(action, rs, params, reader, callback, scope, arg) {
\r
3358 var p = Ext.urlEncode(Ext.apply(params, this.extraParams));
\r
3360 var url = this.buildUrl(action, rs);
\r
3362 throw new Ext.data.Api.Error('invalid-url', url);
\r
3364 url = Ext.urlAppend(url, p);
\r
3367 url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));
\r
3369 var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
\r
3373 cb : "stcCallback"+transId,
\r
3374 scriptId : "stcScript"+transId,
\r
3378 callback : callback,
\r
3382 window[trans.cb] = this.createCallback(action, rs, trans);
\r
3383 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
\r
3384 if(this.autoAbort !== false){
\r
3388 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
\r
3390 var script = document.createElement("script");
\r
3391 script.setAttribute("src", url);
\r
3392 script.setAttribute("type", "text/javascript");
\r
3393 script.setAttribute("id", trans.scriptId);
\r
3394 this.head.appendChild(script);
\r
3396 this.trans = trans;
\r
3399 // @private createCallback
\r
3400 createCallback : function(action, rs, trans) {
\r
3402 return function(res) {
\r
3403 self.trans = false;
\r
3404 self.destroyTrans(trans, true);
\r
3405 if (action === Ext.data.Api.actions.read) {
\r
3406 self.onRead.call(self, action, trans, res);
\r
3408 self.onWrite.call(self, action, trans, res, rs);
\r
3413 * Callback for read actions
\r
3414 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
\r
3415 * @param {Object} trans The request transaction object
\r
3416 * @param {Object} res The server response
\r
3419 onRead : function(action, trans, res) {
\r
3422 result = trans.reader.readRecords(res);
\r
3424 // @deprecated: fire loadexception
\r
3425 this.fireEvent("loadexception", this, trans, res, e);
\r
3427 this.fireEvent('exception', this, 'response', action, trans, res, e);
\r
3428 trans.callback.call(trans.scope||window, null, trans.arg, false);
\r
3431 if (result.success === false) {
\r
3432 // @deprecated: fire old loadexception for backwards-compat.
\r
3433 this.fireEvent('loadexception', this, trans, res);
\r
3435 this.fireEvent('exception', this, 'remote', action, trans, res, null);
\r
3437 this.fireEvent("load", this, res, trans.arg);
\r
3439 trans.callback.call(trans.scope||window, result, trans.arg, result.success);
\r
3442 * Callback for write actions
\r
3443 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
\r
3444 * @param {Object} trans The request transaction object
\r
3445 * @param {Object} res The server response
\r
3448 onWrite : function(action, trans, res, rs) {
\r
3449 var reader = trans.reader;
\r
3451 // though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.
\r
3452 reader.readResponse(action, res);
\r
3454 this.fireEvent('exception', this, 'response', action, trans, res, e);
\r
3455 trans.callback.call(trans.scope||window, null, res, false);
\r
3458 if(!res[reader.meta.successProperty] === true){
\r
3459 this.fireEvent('exception', this, 'remote', action, trans, res, rs);
\r
3460 trans.callback.call(trans.scope||window, null, res, false);
\r
3463 this.fireEvent("write", this, action, res[reader.meta.root], res, rs, trans.arg );
\r
3464 trans.callback.call(trans.scope||window, res[reader.meta.root], res, true);
\r
3468 isLoading : function(){
\r
3469 return this.trans ? true : false;
\r
3473 * Abort the current server request.
\r
3475 abort : function(){
\r
3476 if(this.isLoading()){
\r
3477 this.destroyTrans(this.trans);
\r
3482 destroyTrans : function(trans, isLoaded){
\r
3483 this.head.removeChild(document.getElementById(trans.scriptId));
\r
3484 clearTimeout(trans.timeoutId);
\r
3486 window[trans.cb] = undefined;
\r
3488 delete window[trans.cb];
\r
3491 // if hasn't been loaded, wait for load to remove it to prevent script error
\r
3492 window[trans.cb] = function(){
\r
3493 window[trans.cb] = undefined;
\r
3495 delete window[trans.cb];
\r
3502 handleFailure : function(trans){
\r
3503 this.trans = false;
\r
3504 this.destroyTrans(trans, false);
\r
3505 if (trans.action === Ext.data.Api.actions.read) {
\r
3506 // @deprecated firing loadexception
\r
3507 this.fireEvent("loadexception", this, null, trans.arg);
\r
3510 this.fireEvent('exception', this, 'response', trans.action, {
\r
3512 options: trans.arg
\r
3514 trans.callback.call(trans.scope||window, null, trans.arg, false);
\r
3518 destroy: function(){
\r
3520 Ext.data.ScriptTagProxy.superclass.destroy.call(this);
\r
3523 * @class Ext.data.HttpProxy
\r
3524 * @extends Ext.data.DataProxy
\r
3525 * <p>An implementation of {@link Ext.data.DataProxy} that processes data requests within the same
\r
3526 * domain of the originating page.</p>
\r
3527 * <p><b>Note</b>: this class cannot be used to retrieve data from a domain other
\r
3528 * than the domain from which the running page was served. For cross-domain requests, use a
\r
3529 * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p>
\r
3530 * <p>Be aware that to enable the browser to parse an XML document, the server must set
\r
3531 * the Content-Type header in the HTTP response to "<tt>text/xml</tt>".</p>
\r
3533 * @param {Object} conn
\r
3534 * An {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.
\r
3535 * <p>Note that if this HttpProxy is being used by a (@link Ext.data.Store Store}, then the
\r
3536 * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>
\r
3537 * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,
\r
3538 * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be
\r
3539 * used to pass parameters known at instantiation time.</p>
\r
3540 * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make
\r
3541 * the request.</p>
\r
3543 Ext.data.HttpProxy = function(conn){
\r
3544 Ext.data.HttpProxy.superclass.constructor.call(this, conn);
\r
3547 * The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy
\r
3548 * uses to make requests to the server. Properties of this object may be changed dynamically to
\r
3549 * change the way data is requested.
\r
3554 // nullify the connection url. The url param has been copied to 'this' above. The connection
\r
3555 // url will be set during each execution of doRequest when buildUrl is called. This makes it easier for users to override the
\r
3556 // connection url during beforeaction events (ie: beforeload, beforesave, etc). The connection url will be nullified
\r
3557 // after each request as well. Url is always re-defined during doRequest.
\r
3558 this.conn.url = null;
\r
3560 this.useAjax = !conn || !conn.events;
\r
3562 //private. A hash containing active requests, keyed on action [Ext.data.Api.actions.create|read|update|destroy]
\r
3563 var actions = Ext.data.Api.actions;
\r
3564 this.activeRequest = {};
\r
3565 for (var verb in actions) {
\r
3566 this.activeRequest[actions[verb]] = undefined;
\r
3570 Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {
\r
3572 * @cfg {Boolean} restful
\r
3573 * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's
\r
3574 * {@link Ext.data.Record#id id} will be appended to the url (defaults to <tt>false</tt>).</p><br>
\r
3575 * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>
\r
3576 * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the
\r
3577 * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>
\r
3578 * <p>Some MVC (e.g., Ruby on Rails, Merb and Django) support this style of segment based urls
\r
3579 * where the segments in the URL follow the Model-View-Controller approach.</p><pre><code>
\r
3580 * someSite.com/controller/action/id
\r
3582 * Where the segments in the url are typically:<div class="mdetail-params"><ul>
\r
3583 * <li>The first segment : represents the controller class that should be invoked.</li>
\r
3584 * <li>The second segment : represents the class function, or method, that should be called.</li>
\r
3585 * <li>The third segment : represents the ID (a variable typically passed to the method).</li>
\r
3587 * <p>For example:</p>
\r
3590 load : '/controller/load',
\r
3591 create : '/controller/new', // Server MUST return idProperty of new record
\r
3592 save : '/controller/update',
\r
3593 destroy : '/controller/destroy_action'
\r
3596 // Alternatively, one can use the object-form to specify each API-action
\r
3598 load: {url: 'read.php', method: 'GET'},
\r
3599 create: 'create.php',
\r
3600 destroy: 'destroy.php',
\r
3601 save: 'update.php'
\r
3606 * Return the {@link Ext.data.Connection} object being used by this Proxy.
\r
3607 * @return {Connection} The Connection object. This object may be used to subscribe to events on
\r
3608 * a finer-grained basis than the DataProxy events.
\r
3610 getConnection : function() {
\r
3611 return this.useAjax ? Ext.Ajax : this.conn;
\r
3615 * Used for overriding the url used for a single request. Designed to be called during a beforeaction event. Calling setUrl
\r
3616 * will override any urls set via the api configuration parameter. Set the optional parameter makePermanent to set the url for
\r
3617 * all subsequent requests. If not set to makePermanent, the next request will use the same url or api configuration defined
\r
3618 * in the initial proxy configuration.
\r
3619 * @param {String} url
\r
3620 * @param {Boolean} makePermanent (Optional) [false]
\r
3622 * (e.g.: beforeload, beforesave, etc).
\r
3624 setUrl : function(url, makePermanent) {
\r
3625 this.conn.url = url;
\r
3626 if (makePermanent === true) {
\r
3628 Ext.data.Api.prepare(this);
\r
3633 * HttpProxy implementation of DataProxy#doRequest
\r
3634 * @param {String} action The crud action type (create, read, update, destroy)
\r
3635 * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
\r
3636 * @param {Object} params An object containing properties which are to be used as HTTP parameters
\r
3637 * for the request to the remote server.
\r
3638 * @param {Ext.data.DataReader} reader The Reader object which converts the data
\r
3639 * object into a block of Ext.data.Records.
\r
3640 * @param {Function} callback
\r
3641 * <div class="sub-desc"><p>A function to be called after the request.
\r
3642 * The <tt>callback</tt> is passed the following arguments:<ul>
\r
3643 * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>
\r
3644 * <li><tt>options</tt>: Options object from the action request</li>
\r
3645 * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>
\r
3646 * @param {Object} scope The scope in which to call the callback
\r
3647 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
\r
3649 doRequest : function(action, rs, params, reader, cb, scope, arg) {
\r
3651 method: (this.api[action]) ? this.api[action]['method'] : undefined,
\r
3658 callback : this.createCallback(action, rs),
\r
3661 // Sample the request data: If it's an object, then it hasn't been json-encoded yet.
\r
3662 // Transmit data using jsonData config of Ext.Ajax.request
\r
3663 if (typeof(params[reader.meta.root]) === 'object') {
\r
3664 o.jsonData = params;
\r
3666 o.params = params || {};
\r
3668 // Set the connection url. If this.conn.url is not null here,
\r
3669 // the user may have overridden the url during a beforeaction event-handler.
\r
3670 // this.conn.url is nullified after each request.
\r
3671 if (this.conn.url === null) {
\r
3672 this.conn.url = this.buildUrl(action, rs);
\r
3674 else if (this.restful === true && rs instanceof Ext.data.Record && !rs.phantom) {
\r
3675 this.conn.url += '/' + rs.id;
\r
3679 Ext.applyIf(o, this.conn);
\r
3681 // If a currently running request is found for this action, abort it.
\r
3682 if (this.activeRequest[action]) {
\r
3683 // Disabled aborting activeRequest while implementing REST. activeRequest[action] will have to become an array
\r
3684 //Ext.Ajax.abort(this.activeRequest[action]);
\r
3686 this.activeRequest[action] = Ext.Ajax.request(o);
\r
3688 this.conn.request(o);
\r
3690 // request is sent, nullify the connection url in preparation for the next request
\r
3691 this.conn.url = null;
\r
3695 * Returns a callback function for a request. Note a special case is made for the
\r
3696 * read action vs all the others.
\r
3697 * @param {String} action [create|update|delete|load]
\r
3698 * @param {Ext.data.Record[]} rs The Store-recordset being acted upon
\r
3701 createCallback : function(action, rs) {
\r
3702 return function(o, success, response) {
\r
3703 this.activeRequest[action] = undefined;
\r
3705 if (action === Ext.data.Api.actions.read) {
\r
3706 // @deprecated: fire loadexception for backwards compat.
\r
3707 this.fireEvent('loadexception', this, o, response);
\r
3709 this.fireEvent('exception', this, 'response', action, o, response);
\r
3710 o.request.callback.call(o.request.scope, null, o.request.arg, false);
\r
3713 if (action === Ext.data.Api.actions.read) {
\r
3714 this.onRead(action, o, response);
\r
3716 this.onWrite(action, o, response, rs);
\r
3722 * Callback for read action
\r
3723 * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.
\r
3724 * @param {Object} o The request transaction object
\r
3725 * @param {Object} res The server response
\r
3728 onRead : function(action, o, response) {
\r
3731 result = o.reader.read(response);
\r
3733 // @deprecated: fire old loadexception for backwards-compat.
\r
3734 this.fireEvent('loadexception', this, o, response, e);
\r
3735 this.fireEvent('exception', this, 'response', action, o, response, e);
\r
3736 o.request.callback.call(o.request.scope, null, o.request.arg, false);
\r
3739 if (result.success === false) {
\r
3740 // @deprecated: fire old loadexception for backwards-compat.
\r
3741 this.fireEvent('loadexception', this, o, response);
\r
3743 // Get DataReader read-back a response-object to pass along to exception event
\r
3744 var res = o.reader.readResponse(action, response);
\r
3745 this.fireEvent('exception', this, 'remote', action, o, res, null);
\r
3748 this.fireEvent('load', this, o, o.request.arg);
\r
3750 o.request.callback.call(o.request.scope, result, o.request.arg, result.success);
\r
3753 * Callback for write actions
\r
3754 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
\r
3755 * @param {Object} trans The request transaction object
\r
3756 * @param {Object} res The server response
\r
3759 onWrite : function(action, o, response, rs) {
\r
3760 var reader = o.reader;
\r
3763 res = reader.readResponse(action, response);
\r
3765 this.fireEvent('exception', this, 'response', action, o, response, e);
\r
3766 o.request.callback.call(o.request.scope, null, o.request.arg, false);
\r
3769 if (res[reader.meta.successProperty] === false) {
\r
3770 this.fireEvent('exception', this, 'remote', action, o, res, rs);
\r
3772 this.fireEvent('write', this, action, res[reader.meta.root], res, rs, o.request.arg);
\r
3774 o.request.callback.call(o.request.scope, res[reader.meta.root], res, res[reader.meta.successProperty]);
\r
3778 destroy: function(){
\r
3779 if(!this.useAjax){
\r
3780 this.conn.abort();
\r
3781 }else if(this.activeRequest){
\r
3782 var actions = Ext.data.Api.actions;
\r
3783 for (var verb in actions) {
\r
3784 if(this.activeRequest[actions[verb]]){
\r
3785 Ext.Ajax.abort(this.activeRequest[actions[verb]]);
\r
3789 Ext.data.HttpProxy.superclass.destroy.call(this);
\r
3792 * @class Ext.data.MemoryProxy
\r
3793 * @extends Ext.data.DataProxy
\r
3794 * An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor
\r
3795 * to the Reader when its load method is called.
\r
3797 * @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.
\r
3799 Ext.data.MemoryProxy = function(data){
\r
3800 // Must define a dummy api with "read" action to satisfy DataProxy#doRequest and Ext.data.Api#prepare *before* calling super
\r
3802 api[Ext.data.Api.actions.read] = true;
\r
3803 Ext.data.MemoryProxy.superclass.constructor.call(this, {
\r
3809 Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {
\r
3811 * @event loadexception
\r
3812 * Fires if an exception occurs in the Proxy during data loading. Note that this event is also relayed
\r
3813 * through {@link Ext.data.Store}, so you can listen for it directly on any Store instance.
\r
3814 * @param {Object} this
\r
3815 * @param {Object} arg The callback's arg object passed to the {@link #load} function
\r
3816 * @param {Object} null This parameter does not apply and will always be null for MemoryProxy
\r
3817 * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data
\r
3821 * MemoryProxy implementation of DataProxy#doRequest
\r
3822 * @param {String} action
\r
3823 * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
\r
3824 * @param {Object} params An object containing properties which are to be used as HTTP parameters
\r
3825 * for the request to the remote server.
\r
3826 * @param {Ext.data.DataReader} reader The Reader object which converts the data
\r
3827 * object into a block of Ext.data.Records.
\r
3828 * @param {Function} callback The function into which to pass the block of Ext.data.Records.
\r
3829 * The function must be passed <ul>
\r
3830 * <li>The Record block object</li>
\r
3831 * <li>The "arg" argument from the load function</li>
\r
3832 * <li>A boolean success indicator</li>
\r
3834 * @param {Object} scope The scope in which to call the callback
\r
3835 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
\r
3837 doRequest : function(action, rs, params, reader, callback, scope, arg) {
\r
3838 // No implementation for CRUD in MemoryProxy. Assumes all actions are 'load'
\r
3839 params = params || {};
\r
3842 result = reader.readRecords(this.data);
\r
3844 // @deprecated loadexception
\r
3845 this.fireEvent("loadexception", this, null, arg, e);
\r
3847 this.fireEvent('exception', this, 'response', action, arg, null, e);
\r
3848 callback.call(scope, null, arg, false);
\r
3851 callback.call(scope, result, arg, true);
\r