Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / data / Store.js
1 /*!
2  * Ext JS Library 3.1.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.data.Store
9  * @extends Ext.util.Observable
10  * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
11  * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
12  * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
13  * <p><u>Retrieving Data</u></p>
14  * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
15  * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
16  * <li>{@link #data} to automatically pass in data</li>
17  * <li>{@link #loadData} to manually pass in data</li>
18  * </ul></div></p>
19  * <p><u>Reading Data</u></p>
20  * <p>A Store object has no inherent knowledge of the format of the data object (it could be
21  * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
22  * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
23  * object.</p>
24  * <p><u>Store Types</u></p>
25  * <p>There are several implementations of Store available which are customized for use with
26  * a specific DataReader implementation.  Here is an example using an ArrayStore which implicitly
27  * creates a reader commensurate to an Array data object.</p>
28  * <pre><code>
29 var myStore = new Ext.data.ArrayStore({
30     fields: ['fullname', 'first'],
31     idIndex: 0 // id for each record will be the first element
32 });
33  * </code></pre>
34  * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
35  * <pre><code>
36 // create a {@link Ext.data.Record Record} constructor:
37 var rt = Ext.data.Record.create([
38     {name: 'fullname'},
39     {name: 'first'}
40 ]);
41 var myStore = new Ext.data.Store({
42     // explicitly create reader
43     reader: new Ext.data.ArrayReader(
44         {
45             idIndex: 0  // id for each record will be the first element
46         },
47         rt // recordType
48     )
49 });
50  * </code></pre>
51  * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
52  * <pre><code>
53 var myData = [
54     [1, 'Fred Flintstone', 'Fred'],  // note that id for the record is the first element
55     [2, 'Barney Rubble', 'Barney']
56 ];
57 myStore.loadData(myData);
58  * </code></pre>
59  * <p>Records are cached and made available through accessor functions.  An example of adding
60  * a record to the store:</p>
61  * <pre><code>
62 var defaultData = {
63     fullname: 'Full Name',
64     first: 'First Name'
65 };
66 var recId = 100; // provide unique id for the record
67 var r = new myStore.recordType(defaultData, ++recId); // create new record
68 myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
69  * </code></pre>
70  * <p><u>Writing Data</u></p>
71  * <p>And <b>new in Ext version 3</b>, use the new {@link Ext.data.DataWriter DataWriter} to create an automated, <a href="http://extjs.com/deploy/dev/examples/writer/writer.html">Writable Store</a>
72  * along with <a href="http://extjs.com/deploy/dev/examples/restful/restful.html">RESTful features.</a>
73  * @constructor
74  * Creates a new Store.
75  * @param {Object} config A config object containing the objects needed for the Store to access data,
76  * and read the data into Records.
77  * @xtype store
78  */
79 Ext.data.Store = Ext.extend(Ext.util.Observable, {
80     /**
81      * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
82      * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
83      * assignment.</p>
84      */
85     /**
86      * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
87      * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
88      * Typically this option, or the <code>{@link #data}</code> option will be specified.
89      */
90     /**
91      * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
92      * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
93      * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
94      * be passed to the store's {@link #load} method.
95      */
96     /**
97      * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
98      * access to a data object.  See <code>{@link #url}</code>.
99      */
100     /**
101      * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
102      * Typically this option, or the <code>{@link #url}</code> option will be specified.
103      */
104     /**
105      * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
106      * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
107      * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
108      */
109     /**
110      * @cfg {Ext.data.DataWriter} writer
111      * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
112      * to the server-side database.</p>
113      * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
114      * events on the store are monitored in order to remotely {@link #createRecords create records},
115      * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
116      * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
117      * <br><p>Sample implementation:
118      * <pre><code>
119 var writer = new {@link Ext.data.JsonWriter}({
120     encode: true,
121     writeAllFields: true // write all fields, not just those that changed
122 });
123
124 // Typical Store collecting the Proxy, Reader and Writer together.
125 var store = new Ext.data.Store({
126     storeId: 'user',
127     root: 'records',
128     proxy: proxy,
129     reader: reader,
130     writer: writer,     // <-- plug a DataWriter into the store just as you would a Reader
131     paramsAsHash: true,
132     autoSave: false    // <-- false to delay executing create, update, destroy requests
133                         //     until specifically told to do so.
134 });
135      * </code></pre></p>
136      */
137     writer : undefined,
138     /**
139      * @cfg {Object} baseParams
140      * <p>An object containing properties which are to be sent as parameters
141      * for <i>every</i> HTTP request.</p>
142      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
143      * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
144      * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
145      * for more details.</p>
146      * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
147      * method.
148      * @property
149      */
150     /**
151      * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
152      * {@link #load} operation.  Note that for local sorting, the <tt>direction</tt> property is
153      * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
154      * For example:<pre><code>
155 sortInfo: {
156     field: 'fieldName',
157     direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
158 }
159 </code></pre>
160      */
161     /**
162      * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
163      * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
164      * in place (defaults to <tt>false</tt>).
165      * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
166      * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
167      * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
168      * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
169      * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
170      * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
171      * </ul></div></p>
172      */
173     remoteSort : false,
174
175     /**
176      * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
177      * to is destroyed (defaults to <tt>false</tt>).
178      * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
179      */
180     autoDestroy : false,
181
182     /**
183      * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
184      * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
185      * for the accessor method to retrieve the modified records.
186      */
187     pruneModifiedRecords : false,
188
189     /**
190      * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
191      * for the details of what this may contain. This may be useful for accessing any params which were used
192      * to load the current Record cache.
193      * @property
194      */
195     lastOptions : null,
196
197     /**
198      * @cfg {Boolean} autoSave
199      * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
200      * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
201      * to send all modifiedRecords to the server.</p>
202      * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
203      */
204     autoSave : true,
205
206     /**
207      * @cfg {Boolean} batch
208      * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
209      * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
210      * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
211      * to <tt>false</tt>.</p>
212      * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
213      * generated for each record.</p>
214      */
215     batch : true,
216
217     /**
218      * @cfg {Boolean} restful
219      * Defaults to <tt>false</tt>.  Set to <tt>true</tt> to have the Store and the set
220      * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
221      * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
222      * action is described in {@link Ext.data.Api#restActions}.  For additional information
223      * see {@link Ext.data.DataProxy#restful}.
224      * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
225      * internally be set to <tt>false</tt>.</p>
226      */
227     restful: false,
228
229     /**
230      * @cfg {Object} paramNames
231      * <p>An object containing properties which specify the names of the paging and
232      * sorting parameters passed to remote servers when loading blocks of data. By default, this
233      * object takes the following form:</p><pre><code>
234 {
235     start : 'start',  // The parameter name which specifies the start row
236     limit : 'limit',  // The parameter name which specifies number of rows to return
237     sort : 'sort',    // The parameter name which specifies the column to sort on
238     dir : 'dir'       // The parameter name which specifies the sort direction
239 }
240 </code></pre>
241      * <p>The server must produce the requested data block upon receipt of these parameter names.
242      * If different parameter names are required, this property can be overriden using a configuration
243      * property.</p>
244      * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
245      * the parameter names to use in its {@link #load requests}.
246      */
247     paramNames : undefined,
248
249     /**
250      * @cfg {Object} defaultParamNames
251      * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
252      * for all stores, this object should be changed on the store prototype.
253      */
254     defaultParamNames : {
255         start : 'start',
256         limit : 'limit',
257         sort : 'sort',
258         dir : 'dir'
259     },
260
261     // private
262     batchKey : '_ext_batch_',
263
264     constructor : function(config){
265         this.data = new Ext.util.MixedCollection(false);
266         this.data.getKey = function(o){
267             return o.id;
268         };
269         /**
270          * See the <code>{@link #baseParams corresponding configuration option}</code>
271          * for a description of this property.
272          * To modify this property see <code>{@link #setBaseParam}</code>.
273          * @property
274          */
275         this.baseParams = {};
276
277         // temporary removed-records cache
278         this.removed = [];
279
280         if(config && config.data){
281             this.inlineData = config.data;
282             delete config.data;
283         }
284
285         Ext.apply(this, config);
286
287         this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
288
289         if((this.url || this.api) && !this.proxy){
290             this.proxy = new Ext.data.HttpProxy({url: this.url, api: this.api});
291         }
292         // If Store is RESTful, so too is the DataProxy
293         if (this.restful === true && this.proxy) {
294             // When operating RESTfully, a unique transaction is generated for each record.
295             // TODO might want to allow implemention of faux REST where batch is possible using RESTful routes only.
296             this.batch = false;
297             Ext.data.Api.restify(this.proxy);
298         }
299
300         if(this.reader){ // reader passed
301             if(!this.recordType){
302                 this.recordType = this.reader.recordType;
303             }
304             if(this.reader.onMetaChange){
305                 this.reader.onMetaChange = this.reader.onMetaChange.createSequence(this.onMetaChange, this);
306             }
307             if (this.writer) { // writer passed
308                 if (this.writer instanceof(Ext.data.DataWriter) === false) {    // <-- config-object instead of instance.
309                     this.writer = this.buildWriter(this.writer);
310                 }
311                 this.writer.meta = this.reader.meta;
312                 this.pruneModifiedRecords = true;
313             }
314         }
315
316         /**
317          * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
318          * {@link Ext.data.DataReader Reader}. Read-only.
319          * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
320          * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
321          * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
322          * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
323     // create the data store
324     var store = new Ext.data.ArrayStore({
325         autoDestroy: true,
326         fields: [
327            {name: 'company'},
328            {name: 'price', type: 'float'},
329            {name: 'change', type: 'float'},
330            {name: 'pctChange', type: 'float'},
331            {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
332         ]
333     });
334     store.loadData(myData);
335
336     // create the Grid
337     var grid = new Ext.grid.EditorGridPanel({
338         store: store,
339         colModel: new Ext.grid.ColumnModel({
340             columns: [
341                 {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
342                 {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
343                 {header: 'Change', renderer: change, dataIndex: 'change'},
344                 {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
345                 {header: 'Last Updated', width: 85,
346                     renderer: Ext.util.Format.dateRenderer('m/d/Y'),
347                     dataIndex: 'lastChange'}
348             ],
349             defaults: {
350                 sortable: true,
351                 width: 75
352             }
353         }),
354         autoExpandColumn: 'company', // match the id specified in the column model
355         height:350,
356         width:600,
357         title:'Array Grid',
358         tbar: [{
359             text: 'Add Record',
360             handler : function(){
361                 var defaultData = {
362                     change: 0,
363                     company: 'New Company',
364                     lastChange: (new Date()).clearTime(),
365                     pctChange: 0,
366                     price: 10
367                 };
368                 var recId = 3; // provide unique id
369                 var p = new store.recordType(defaultData, recId); // create new record
370                 grid.stopEditing();
371                 store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
372                 grid.startEditing(0, 0);
373             }
374         }]
375     });
376          * </code></pre>
377          * @property recordType
378          * @type Function
379          */
380
381         if(this.recordType){
382             /**
383              * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
384              * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
385              * @property fields
386              * @type Ext.util.MixedCollection
387              */
388             this.fields = this.recordType.prototype.fields;
389         }
390         this.modified = [];
391
392         this.addEvents(
393             /**
394              * @event datachanged
395              * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
396              * widget that is using this Store as a Record cache should refresh its view.
397              * @param {Store} this
398              */
399             'datachanged',
400             /**
401              * @event metachange
402              * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
403              * @param {Store} this
404              * @param {Object} meta The JSON metadata
405              */
406             'metachange',
407             /**
408              * @event add
409              * Fires when Records have been {@link #add}ed to the Store
410              * @param {Store} this
411              * @param {Ext.data.Record[]} records The array of Records added
412              * @param {Number} index The index at which the record(s) were added
413              */
414             'add',
415             /**
416              * @event remove
417              * Fires when a Record has been {@link #remove}d from the Store
418              * @param {Store} this
419              * @param {Ext.data.Record} record The Record that was removed
420              * @param {Number} index The index at which the record was removed
421              */
422             'remove',
423             /**
424              * @event update
425              * Fires when a Record has been updated
426              * @param {Store} this
427              * @param {Ext.data.Record} record The Record that was updated
428              * @param {String} operation The update operation being performed.  Value may be one of:
429              * <pre><code>
430      Ext.data.Record.EDIT
431      Ext.data.Record.REJECT
432      Ext.data.Record.COMMIT
433              * </code></pre>
434              */
435             'update',
436             /**
437              * @event clear
438              * Fires when the data cache has been cleared.
439              * @param {Store} this
440              * @param {Record[]} The records that were cleared.
441              */
442             'clear',
443             /**
444              * @event exception
445              * <p>Fires if an exception occurs in the Proxy during a remote request.
446              * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
447              * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
448              * for additional details.
449              * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
450              * for description.
451              */
452             'exception',
453             /**
454              * @event beforeload
455              * Fires before a request is made for a new data object.  If the beforeload handler returns
456              * <tt>false</tt> the {@link #load} action will be canceled.
457              * @param {Store} this
458              * @param {Object} options The loading options that were specified (see {@link #load} for details)
459              */
460             'beforeload',
461             /**
462              * @event load
463              * Fires after a new set of Records has been loaded.
464              * @param {Store} this
465              * @param {Ext.data.Record[]} records The Records that were loaded
466              * @param {Object} options The loading options that were specified (see {@link #load} for details)
467              */
468             'load',
469             /**
470              * @event loadexception
471              * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
472              * event instead.</p>
473              * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
474              * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
475              * for additional details.
476              * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
477              * for description.
478              */
479             'loadexception',
480             /**
481              * @event beforewrite
482              * @param {Ext.data.Store} store
483              * @param {String} action [Ext.data.Api.actions.create|update|destroy]
484              * @param {Record/Array[Record]} rs
485              * @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)
486              * @param {Object} arg The callback's arg object passed to the {@link #request} function
487              */
488             'beforewrite',
489             /**
490              * @event write
491              * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
492              * Success of the action is determined in the <code>result['successProperty']</code>property (<b>NOTE</b> for RESTful stores,
493              * a simple 20x response is sufficient for the actions "destroy" and "update".  The "create" action should should return 200 along with a database pk).
494              * @param {Ext.data.Store} store
495              * @param {String} action [Ext.data.Api.actions.create|update|destroy]
496              * @param {Object} result The 'data' picked-out out of the response for convenience.
497              * @param {Ext.Direct.Transaction} res
498              * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
499              */
500             'write',
501             /**
502              * @event beforesave
503              * Fires before a save action is called. A save encompasses destroying records, updating records and creating records.
504              * @param {Ext.data.Store} store
505              * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
506              * with an array of records for each action.
507              */
508             'beforesave',
509             /**
510              * @event save
511              * Fires after a save is completed. A save encompasses destroying records, updating records and creating records.
512              * @param {Ext.data.Store} store
513              * @param {Number} batch The identifier for the batch that was saved.
514              * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
515              * with an array of records for each action.
516              */
517             'save'
518
519         );
520
521         if(this.proxy){
522             // TODO remove deprecated loadexception with ext-3.0.1
523             this.relayEvents(this.proxy,  ['loadexception', 'exception']);
524         }
525         // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
526         if (this.writer) {
527             this.on({
528                 scope: this,
529                 add: this.createRecords,
530                 remove: this.destroyRecord,
531                 update: this.updateRecord,
532                 clear: this.onClear
533             });
534         }
535
536         this.sortToggle = {};
537         if(this.sortField){
538             this.setDefaultSort(this.sortField, this.sortDir);
539         }else if(this.sortInfo){
540             this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
541         }
542
543         Ext.data.Store.superclass.constructor.call(this);
544
545         if(this.id){
546             this.storeId = this.id;
547             delete this.id;
548         }
549         if(this.storeId){
550             Ext.StoreMgr.register(this);
551         }
552         if(this.inlineData){
553             this.loadData(this.inlineData);
554             delete this.inlineData;
555         }else if(this.autoLoad){
556             this.load.defer(10, this, [
557                 typeof this.autoLoad == 'object' ?
558                     this.autoLoad : undefined]);
559         }
560         // used internally to uniquely identify a batch
561         this.batchCounter = 0;
562         this.batches = {};
563     },
564
565     /**
566      * builds a DataWriter instance when Store constructor is provided with a writer config-object instead of an instace.
567      * @param {Object} config Writer configuration
568      * @return {Ext.data.DataWriter}
569      * @private
570      */
571     buildWriter : function(config) {
572         var klass = undefined;
573         type = (config.format || 'json').toLowerCase();
574         switch (type) {
575             case 'json':
576                 klass = Ext.data.JsonWriter;
577                 break;
578             case 'xml':
579                 klass = Ext.data.XmlWriter;
580                 break;
581             default:
582                 klass = Ext.data.JsonWriter;
583         }
584         return new klass(config);
585     },
586
587     /**
588      * Destroys the store.
589      */
590     destroy : function(){
591         if(!this.isDestroyed){
592             if(this.storeId){
593                 Ext.StoreMgr.unregister(this);
594             }
595             this.clearData();
596             this.data = null;
597             Ext.destroy(this.proxy);
598             this.reader = this.writer = null;
599             this.purgeListeners();
600             this.isDestroyed = true;
601         }
602     },
603
604     /**
605      * Add Records to the Store and fires the {@link #add} event.  To add Records
606      * to the store from a remote source use <code>{@link #load}({add:true})</code>.
607      * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
608      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
609      * to add to the cache. See {@link #recordType}.
610      */
611     add : function(records){
612         records = [].concat(records);
613         if(records.length < 1){
614             return;
615         }
616         for(var i = 0, len = records.length; i < len; i++){
617             records[i].join(this);
618         }
619         var index = this.data.length;
620         this.data.addAll(records);
621         if(this.snapshot){
622             this.snapshot.addAll(records);
623         }
624         this.fireEvent('add', this, records, index);
625     },
626
627     /**
628      * (Local sort only) Inserts the passed Record into the Store at the index where it
629      * should go based on the current sort information.
630      * @param {Ext.data.Record} record
631      */
632     addSorted : function(record){
633         var index = this.findInsertIndex(record);
634         this.insert(index, record);
635     },
636
637     /**
638      * Remove Records from the Store and fires the {@link #remove} event.
639      * @param {Ext.data.Record/Ext.data.Record[]} record The record object or array of records to remove from the cache.
640      */
641     remove : function(record){
642         if(Ext.isArray(record)){
643             Ext.each(record, function(r){
644                 this.remove(r);
645             }, this);
646         }
647         var index = this.data.indexOf(record);
648         if(index > -1){
649             record.join(null);
650             this.data.removeAt(index);
651         }
652         if(this.pruneModifiedRecords){
653             this.modified.remove(record);
654         }
655         if(this.snapshot){
656             this.snapshot.remove(record);
657         }
658         if(index > -1){
659             this.fireEvent('remove', this, record, index);
660         }
661     },
662
663     /**
664      * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
665      * @param {Number} index The index of the record to remove.
666      */
667     removeAt : function(index){
668         this.remove(this.getAt(index));
669     },
670
671     /**
672      * Remove all Records from the Store and fires the {@link #clear} event.
673      * @param {Boolean} silent [false] Defaults to <tt>false</tt>.  Set <tt>true</tt> to not fire clear event.
674      */
675     removeAll : function(silent){
676         var items = [];
677         this.each(function(rec){
678             items.push(rec);
679         });
680         this.clearData();
681         if(this.snapshot){
682             this.snapshot.clear();
683         }
684         if(this.pruneModifiedRecords){
685             this.modified = [];
686         }
687         if (silent !== true) {  // <-- prevents write-actions when we just want to clear a store.
688             this.fireEvent('clear', this, items);
689         }
690     },
691
692     // private
693     onClear: function(store, records){
694         Ext.each(records, function(rec, index){
695             this.destroyRecord(this, rec, index);
696         }, this);
697     },
698
699     /**
700      * Inserts Records into the Store at the given index and fires the {@link #add} event.
701      * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
702      * @param {Number} index The start index at which to insert the passed Records.
703      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
704      */
705     insert : function(index, records){
706         records = [].concat(records);
707         for(var i = 0, len = records.length; i < len; i++){
708             this.data.insert(index, records[i]);
709             records[i].join(this);
710         }
711         if(this.snapshot){
712             this.snapshot.addAll(records);
713         }
714         this.fireEvent('add', this, records, index);
715     },
716
717     /**
718      * Get the index within the cache of the passed Record.
719      * @param {Ext.data.Record} record The Ext.data.Record object to find.
720      * @return {Number} The index of the passed Record. Returns -1 if not found.
721      */
722     indexOf : function(record){
723         return this.data.indexOf(record);
724     },
725
726     /**
727      * Get the index within the cache of the Record with the passed id.
728      * @param {String} id The id of the Record to find.
729      * @return {Number} The index of the Record. Returns -1 if not found.
730      */
731     indexOfId : function(id){
732         return this.data.indexOfKey(id);
733     },
734
735     /**
736      * Get the Record with the specified id.
737      * @param {String} id The id of the Record to find.
738      * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
739      */
740     getById : function(id){
741         return (this.snapshot || this.data).key(id);
742     },
743
744     /**
745      * Get the Record at the specified index.
746      * @param {Number} index The index of the Record to find.
747      * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
748      */
749     getAt : function(index){
750         return this.data.itemAt(index);
751     },
752
753     /**
754      * Returns a range of Records between specified indices.
755      * @param {Number} startIndex (optional) The starting index (defaults to 0)
756      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
757      * @return {Ext.data.Record[]} An array of Records
758      */
759     getRange : function(start, end){
760         return this.data.getRange(start, end);
761     },
762
763     // private
764     storeOptions : function(o){
765         o = Ext.apply({}, o);
766         delete o.callback;
767         delete o.scope;
768         this.lastOptions = o;
769     },
770
771     // private
772     clearData: function(){
773         this.data.each(function(rec) {
774             rec.join(null);
775         });
776         this.data.clear();
777     },
778
779     /**
780      * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
781      * <br><p>Notes:</p><div class="mdetail-params"><ul>
782      * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
783      * loaded. To perform any post-processing where information from the load call is required, specify
784      * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
785      * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
786      * properties in the <code>options.params</code> property to establish the initial position within the
787      * dataset, and the number of Records to cache on each read from the Proxy.</li>
788      * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
789      * will be automatically included with the posted parameters according to the specified
790      * <code>{@link #paramNames}</code>.</li>
791      * </ul></div>
792      * @param {Object} options An object containing properties which control loading options:<ul>
793      * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
794      * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
795      * <code>{@link #baseParams}</code> of the same name.</p>
796      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
797      * <li><b>callback</b> : Function<div class="sub-desc"><p>A function to be called after the Records
798      * have been loaded. The callback is called after the load event is fired, and is passed the following arguments:<ul>
799      * <li>r : Ext.data.Record[] An Array of Records loaded.</li>
800      * <li>options : Options object from the load call.</li>
801      * <li>success : Boolean success indicator.</li></ul></p></div></li>
802      * <li><b>scope</b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
803      * to the Store object)</p></div></li>
804      * <li><b>add</b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
805      * replace the current cache.  <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
806      * </ul>
807      * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
808      * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
809      */
810     load : function(options) {
811         options = options || {};
812         this.storeOptions(options);
813         if(this.sortInfo && this.remoteSort){
814             var pn = this.paramNames;
815             options.params = options.params || {};
816             options.params[pn.sort] = this.sortInfo.field;
817             options.params[pn.dir] = this.sortInfo.direction;
818         }
819         try {
820             return this.execute('read', null, options); // <-- null represents rs.  No rs for load actions.
821         } catch(e) {
822             this.handleException(e);
823             return false;
824         }
825     },
826
827     /**
828      * updateRecord  Should not be used directly.  This method will be called automatically if a Writer is set.
829      * Listens to 'update' event.
830      * @param {Object} store
831      * @param {Object} record
832      * @param {Object} action
833      * @private
834      */
835     updateRecord : function(store, record, action) {
836         if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid()))) {
837             this.save();
838         }
839     },
840
841     /**
842      * Should not be used directly.  Store#add will call this automatically if a Writer is set
843      * @param {Object} store
844      * @param {Object} rs
845      * @param {Object} index
846      * @private
847      */
848     createRecords : function(store, rs, index) {
849         for (var i = 0, len = rs.length; i < len; i++) {
850             if (rs[i].phantom && rs[i].isValid()) {
851                 rs[i].markDirty();  // <-- Mark new records dirty
852                 this.modified.push(rs[i]);  // <-- add to modified
853             }
854         }
855         if (this.autoSave === true) {
856             this.save();
857         }
858     },
859
860     /**
861      * Destroys a record or records.  Should not be used directly.  It's called by Store#remove if a Writer is set.
862      * @param {Store} this
863      * @param {Ext.data.Record/Ext.data.Record[]}
864      * @param {Number} index
865      * @private
866      */
867     destroyRecord : function(store, record, index) {
868         if (this.modified.indexOf(record) != -1) {  // <-- handled already if @cfg pruneModifiedRecords == true
869             this.modified.remove(record);
870         }
871         if (!record.phantom) {
872             this.removed.push(record);
873
874             // since the record has already been removed from the store but the server request has not yet been executed,
875             // must keep track of the last known index this record existed.  If a server error occurs, the record can be
876             // put back into the store.  @see Store#createCallback where the record is returned when response status === false
877             record.lastIndex = index;
878
879             if (this.autoSave === true) {
880                 this.save();
881             }
882         }
883     },
884
885     /**
886      * This method should generally not be used directly.  This method is called internally
887      * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
888      * {@link #remove}, or {@link #update} events fire.
889      * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
890      * @param {Record/Record[]} rs
891      * @param {Object} options
892      * @throws Error
893      * @private
894      */
895     execute : function(action, rs, options, /* private */ batch) {
896         // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
897         if (!Ext.data.Api.isAction(action)) {
898             throw new Ext.data.Api.Error('execute', action);
899         }
900         // make sure options has a fresh, new params hash
901         options = Ext.applyIf(options||{}, {
902             params: {}
903         });
904         if(batch !== undefined){
905             this.addToBatch(batch);
906         }
907         // have to separate before-events since load has a different signature than create,destroy and save events since load does not
908         // include the rs (record resultset) parameter.  Capture return values from the beforeaction into doRequest flag.
909         var doRequest = true;
910
911         if (action === 'read') {
912             Ext.applyIf(options.params, this.baseParams);
913             doRequest = this.fireEvent('beforeload', this, options);
914         }
915         else {
916             // if Writer is configured as listful, force single-record rs to be [{}] instead of {}
917             // TODO Move listful rendering into DataWriter where the @cfg is defined.  Should be easy now.
918             if (this.writer.listful === true && this.restful !== true) {
919                 rs = (Ext.isArray(rs)) ? rs : [rs];
920             }
921             // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
922             else if (Ext.isArray(rs) && rs.length == 1) {
923                 rs = rs.shift();
924             }
925             // Write the action to options.params
926             if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
927                 this.writer.apply(options.params, this.baseParams, action, rs);
928             }
929         }
930         if (doRequest !== false) {
931             // Send request to proxy.
932             if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
933                 options.params.xaction = action;    // <-- really old, probaby unecessary.
934             }
935             // Note:  Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.
936             // We'll flip it now and send the value into DataProxy#request, since it's the value which maps to
937             // the user's configured DataProxy#api
938             // TODO Refactor all Proxies to accept an instance of Ext.data.Request (not yet defined) instead of this looooooong list
939             // of params.  This method is an artifact from Ext2.
940             this.proxy.request(Ext.data.Api.actions[action], rs, options.params, this.reader, this.createCallback(action, rs, batch), this, options);
941         }
942         return doRequest;
943     },
944
945     /**
946      * Saves all pending changes to the store.  If the commensurate Ext.data.Api.actions action is not configured, then
947      * the configured <code>{@link #url}</code> will be used.
948      * <pre>
949      * change            url
950      * ---------------   --------------------
951      * removed records   Ext.data.Api.actions.destroy
952      * phantom records   Ext.data.Api.actions.create
953      * {@link #getModifiedRecords modified records}  Ext.data.Api.actions.update
954      * </pre>
955      * @TODO:  Create extensions of Error class and send associated Record with thrown exceptions.
956      * e.g.:  Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
957      * @return {Number} batch Returns a number to uniquely identify the "batch" of saves occurring. -1 will be returned
958      * if there are no items to save or the save was cancelled.
959      */
960     save : function() {
961         if (!this.writer) {
962             throw new Ext.data.Store.Error('writer-undefined');
963         }
964
965         var queue = [],
966             len,
967             trans,
968             batch,
969             data = {};
970         // DESTROY:  First check for removed records.  Records in this.removed are guaranteed non-phantoms.  @see Store#remove
971         if(this.removed.length){
972             queue.push(['destroy', this.removed]);
973         }
974
975         // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
976         var rs = [].concat(this.getModifiedRecords());
977         if(rs.length){
978             // CREATE:  Next check for phantoms within rs.  splice-off and execute create.
979             var phantoms = [];
980             for(var i = rs.length-1; i >= 0; i--){
981                 if(rs[i].phantom === true){
982                     var rec = rs.splice(i, 1).shift();
983                     if(rec.isValid()){
984                         phantoms.push(rec);
985                     }
986                 }else if(!rs[i].isValid()){ // <-- while we're here, splice-off any !isValid real records
987                     rs.splice(i,1);
988                 }
989             }
990             // If we have valid phantoms, create them...
991             if(phantoms.length){
992                 queue.push(['create', phantoms]);
993             }
994
995             // UPDATE:  And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
996             if(rs.length){
997                 queue.push(['update', rs]);
998             }
999         }
1000         len = queue.length;
1001         if(len){
1002             batch = ++this.batchCounter;
1003             for(var i = 0; i < len; ++i){
1004                 trans = queue[i];
1005                 data[trans[0]] = trans[1];
1006             }
1007             if(this.fireEvent('beforesave', this, data) !== false){
1008                 for(var i = 0; i < len; ++i){
1009                     trans = queue[i];
1010                     this.doTransaction(trans[0], trans[1], batch);
1011                 }
1012                 return batch;
1013             }
1014         }
1015         return -1;
1016     },
1017
1018     // private.  Simply wraps call to Store#execute in try/catch.  Defers to Store#handleException on error.  Loops if batch: false
1019     doTransaction : function(action, rs, batch) {
1020         function transaction(records) {
1021             try{
1022                 this.execute(action, records, undefined, batch);
1023             }catch (e){
1024                 this.handleException(e);
1025             }
1026         }
1027         if(this.batch === false){
1028             for(var i = 0, len = rs.length; i < len; i++){
1029                 transaction.call(this, rs[i]);
1030             }
1031         }else{
1032             transaction.call(this, rs);
1033         }
1034     },
1035
1036     // private
1037     addToBatch : function(batch){
1038         var b = this.batches,
1039             key = this.batchKey + batch,
1040             o = b[key];
1041
1042         if(!o){
1043             b[key] = o = {
1044                 id: batch,
1045                 count: 0,
1046                 data: {}
1047             }
1048         }
1049         ++o.count;
1050     },
1051
1052     removeFromBatch : function(batch, action, data){
1053         var b = this.batches,
1054             key = this.batchKey + batch,
1055             o = b[key],
1056             data,
1057             arr;
1058
1059
1060         if(o){
1061             arr = o.data[action] || [];
1062             o.data[action] = arr.concat(data);
1063             if(o.count === 1){
1064                 data = o.data;
1065                 delete b[key];
1066                 this.fireEvent('save', this, batch, data);
1067             }else{
1068                 --o.count;
1069             }
1070         }
1071     },
1072
1073     // @private callback-handler for remote CRUD actions
1074     // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
1075     createCallback : function(action, rs, batch) {
1076         var actions = Ext.data.Api.actions;
1077         return (action == 'read') ? this.loadRecords : function(data, response, success) {
1078             // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
1079             this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, [].concat(data));
1080             // If success === false here, exception will have been called in DataProxy
1081             if (success === true) {
1082                 this.fireEvent('write', this, action, data, response, rs);
1083             }
1084             this.removeFromBatch(batch, action, data);
1085         };
1086     },
1087
1088     // Clears records from modified array after an exception event.
1089     // NOTE:  records are left marked dirty.  Do we want to commit them even though they were not updated/realized?
1090     // TODO remove this method?
1091     clearModified : function(rs) {
1092         if (Ext.isArray(rs)) {
1093             for (var n=rs.length-1;n>=0;n--) {
1094                 this.modified.splice(this.modified.indexOf(rs[n]), 1);
1095             }
1096         } else {
1097             this.modified.splice(this.modified.indexOf(rs), 1);
1098         }
1099     },
1100
1101     // remap record ids in MixedCollection after records have been realized.  @see Store#onCreateRecords, @see DataReader#realize
1102     reMap : function(record) {
1103         if (Ext.isArray(record)) {
1104             for (var i = 0, len = record.length; i < len; i++) {
1105                 this.reMap(record[i]);
1106             }
1107         } else {
1108             delete this.data.map[record._phid];
1109             this.data.map[record.id] = record;
1110             var index = this.data.keys.indexOf(record._phid);
1111             this.data.keys.splice(index, 1, record.id);
1112             delete record._phid;
1113         }
1114     },
1115
1116     // @protected onCreateRecord proxy callback for create action
1117     onCreateRecords : function(success, rs, data) {
1118         if (success === true) {
1119             try {
1120                 this.reader.realize(rs, data);
1121                 this.reMap(rs);
1122             }
1123             catch (e) {
1124                 this.handleException(e);
1125                 if (Ext.isArray(rs)) {
1126                     // Recurse to run back into the try {}.  DataReader#realize splices-off the rs until empty.
1127                     this.onCreateRecords(success, rs, data);
1128                 }
1129             }
1130         }
1131     },
1132
1133     // @protected, onUpdateRecords proxy callback for update action
1134     onUpdateRecords : function(success, rs, data) {
1135         if (success === true) {
1136             try {
1137                 this.reader.update(rs, data);
1138             } catch (e) {
1139                 this.handleException(e);
1140                 if (Ext.isArray(rs)) {
1141                     // Recurse to run back into the try {}.  DataReader#update splices-off the rs until empty.
1142                     this.onUpdateRecords(success, rs, data);
1143                 }
1144             }
1145         }
1146     },
1147
1148     // @protected onDestroyRecords proxy callback for destroy action
1149     onDestroyRecords : function(success, rs, data) {
1150         // splice each rec out of this.removed
1151         rs = (rs instanceof Ext.data.Record) ? [rs] : [].concat(rs);
1152         for (var i=0,len=rs.length;i<len;i++) {
1153             this.removed.splice(this.removed.indexOf(rs[i]), 1);
1154         }
1155         if (success === false) {
1156             // put records back into store if remote destroy fails.
1157             // @TODO: Might want to let developer decide.
1158             for (i=rs.length-1;i>=0;i--) {
1159                 this.insert(rs[i].lastIndex, rs[i]);    // <-- lastIndex set in Store#destroyRecord
1160             }
1161         }
1162     },
1163
1164     // protected handleException.  Possibly temporary until Ext framework has an exception-handler.
1165     handleException : function(e) {
1166         // @see core/Error.js
1167         Ext.handleError(e);
1168     },
1169
1170     /**
1171      * <p>Reloads the Record cache from the configured Proxy using the configured
1172      * {@link Ext.data.Reader Reader} and the options from the last load operation
1173      * performed.</p>
1174      * <p><b>Note</b>: see the Important note in {@link #load}.</p>
1175      * @param {Object} options <p>(optional) An <tt>Object</tt> containing
1176      * {@link #load loading options} which may override the {@link #lastOptions options}
1177      * used in the last {@link #load} operation. See {@link #load} for details
1178      * (defaults to <tt>null</tt>, in which case the {@link #lastOptions} are
1179      * used).</p>
1180      * <br><p>To add new params to the existing params:</p><pre><code>
1181 lastOptions = myStore.lastOptions;
1182 Ext.apply(lastOptions.params, {
1183     myNewParam: true
1184 });
1185 myStore.reload(lastOptions);
1186      * </code></pre>
1187      */
1188     reload : function(options){
1189         this.load(Ext.applyIf(options||{}, this.lastOptions));
1190     },
1191
1192     // private
1193     // Called as a callback by the Reader during a load operation.
1194     loadRecords : function(o, options, success){
1195         if (this.isDestroyed === true) {
1196             return;
1197         }
1198         if(!o || success === false){
1199             if(success !== false){
1200                 this.fireEvent('load', this, [], options);
1201             }
1202             if(options.callback){
1203                 options.callback.call(options.scope || this, [], options, false, o);
1204             }
1205             return;
1206         }
1207         var r = o.records, t = o.totalRecords || r.length;
1208         if(!options || options.add !== true){
1209             if(this.pruneModifiedRecords){
1210                 this.modified = [];
1211             }
1212             for(var i = 0, len = r.length; i < len; i++){
1213                 r[i].join(this);
1214             }
1215             if(this.snapshot){
1216                 this.data = this.snapshot;
1217                 delete this.snapshot;
1218             }
1219             this.clearData();
1220             this.data.addAll(r);
1221             this.totalLength = t;
1222             this.applySort();
1223             this.fireEvent('datachanged', this);
1224         }else{
1225             this.totalLength = Math.max(t, this.data.length+r.length);
1226             this.add(r);
1227         }
1228         this.fireEvent('load', this, r, options);
1229         if(options.callback){
1230             options.callback.call(options.scope || this, r, options, true);
1231         }
1232     },
1233
1234     /**
1235      * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
1236      * which understands the format of the data must have been configured in the constructor.
1237      * @param {Object} data The data block from which to read the Records.  The format of the data expected
1238      * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
1239      * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
1240      * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
1241      * the existing cache.
1242      * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
1243      * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
1244      * new, unique ids will be added.
1245      */
1246     loadData : function(o, append){
1247         var r = this.reader.readRecords(o);
1248         this.loadRecords(r, {add: append}, true);
1249     },
1250
1251     /**
1252      * Gets the number of cached records.
1253      * <p>If using paging, this may not be the total size of the dataset. If the data object
1254      * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1255      * the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
1256      * @return {Number} The number of Records in the Store's cache.
1257      */
1258     getCount : function(){
1259         return this.data.length || 0;
1260     },
1261
1262     /**
1263      * Gets the total number of records in the dataset as returned by the server.
1264      * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
1265      * must contain the dataset size. For remote data sources, the value for this property
1266      * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
1267      * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
1268      * <b>Note</b>: see the Important note in {@link #load}.</p>
1269      * @return {Number} The number of Records as specified in the data object passed to the Reader
1270      * by the Proxy.
1271      * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
1272      */
1273     getTotalCount : function(){
1274         return this.totalLength || 0;
1275     },
1276
1277     /**
1278      * Returns an object describing the current sort state of this Store.
1279      * @return {Object} The sort state of the Store. An object with two properties:<ul>
1280      * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
1281      * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
1282      * </ul>
1283      * See <tt>{@link #sortInfo}</tt> for additional details.
1284      */
1285     getSortState : function(){
1286         return this.sortInfo;
1287     },
1288
1289     // private
1290     applySort : function(){
1291         if(this.sortInfo && !this.remoteSort){
1292             var s = this.sortInfo, f = s.field;
1293             this.sortData(f, s.direction);
1294         }
1295     },
1296
1297     // private
1298     sortData : function(f, direction){
1299         direction = direction || 'ASC';
1300         var st = this.fields.get(f).sortType;
1301         var fn = function(r1, r2){
1302             var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
1303             return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
1304         };
1305         this.data.sort(direction, fn);
1306         if(this.snapshot && this.snapshot != this.data){
1307             this.snapshot.sort(direction, fn);
1308         }
1309     },
1310
1311     /**
1312      * Sets the default sort column and order to be used by the next {@link #load} operation.
1313      * @param {String} fieldName The name of the field to sort by.
1314      * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1315      */
1316     setDefaultSort : function(field, dir){
1317         dir = dir ? dir.toUpperCase() : 'ASC';
1318         this.sortInfo = {field: field, direction: dir};
1319         this.sortToggle[field] = dir;
1320     },
1321
1322     /**
1323      * Sort the Records.
1324      * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
1325      * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
1326      * @param {String} fieldName The name of the field to sort by.
1327      * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1328      */
1329     sort : function(fieldName, dir){
1330         var f = this.fields.get(fieldName);
1331         if(!f){
1332             return false;
1333         }
1334         if(!dir){
1335             if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
1336                 dir = (this.sortToggle[f.name] || 'ASC').toggle('ASC', 'DESC');
1337             }else{
1338                 dir = f.sortDir;
1339             }
1340         }
1341         var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
1342         var si = (this.sortInfo) ? this.sortInfo : null;
1343
1344         this.sortToggle[f.name] = dir;
1345         this.sortInfo = {field: f.name, direction: dir};
1346         if(!this.remoteSort){
1347             this.applySort();
1348             this.fireEvent('datachanged', this);
1349         }else{
1350             if (!this.load(this.lastOptions)) {
1351                 if (st) {
1352                     this.sortToggle[f.name] = st;
1353                 }
1354                 if (si) {
1355                     this.sortInfo = si;
1356                 }
1357             }
1358         }
1359     },
1360
1361     /**
1362      * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
1363      * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
1364      * Returning <tt>false</tt> aborts and exits the iteration.
1365      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
1366      * Defaults to the current {@link Ext.data.Record Record} in the iteration.
1367      */
1368     each : function(fn, scope){
1369         this.data.each(fn, scope);
1370     },
1371
1372     /**
1373      * Gets all {@link Ext.data.Record records} modified since the last commit.  Modified records are
1374      * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
1375      * included.  See also <tt>{@link #pruneModifiedRecords}</tt> and
1376      * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
1377      * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
1378      * modifications.  To obtain modified fields within a modified record see
1379      *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
1380      */
1381     getModifiedRecords : function(){
1382         return this.modified;
1383     },
1384
1385     // private
1386     createFilterFn : function(property, value, anyMatch, caseSensitive){
1387         if(Ext.isEmpty(value, false)){
1388             return false;
1389         }
1390         value = this.data.createValueMatcher(value, anyMatch, caseSensitive);
1391         return function(r){
1392             return value.test(r.data[property]);
1393         };
1394     },
1395
1396     /**
1397      * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
1398      * and <tt>end</tt> and returns the result.
1399      * @param {String} property A field in each record
1400      * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
1401      * @param {Number} end (optional) The last record index to include (defaults to length - 1)
1402      * @return {Number} The sum
1403      */
1404     sum : function(property, start, end){
1405         var rs = this.data.items, v = 0;
1406         start = start || 0;
1407         end = (end || end === 0) ? end : rs.length-1;
1408
1409         for(var i = start; i <= end; i++){
1410             v += (rs[i].data[property] || 0);
1411         }
1412         return v;
1413     },
1414
1415     /**
1416      * Filter the {@link Ext.data.Record records} by a specified property.
1417      * @param {String} field A field on your records
1418      * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
1419      * against the field.
1420      * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
1421      * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
1422      */
1423     filter : function(property, value, anyMatch, caseSensitive){
1424         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1425         return fn ? this.filterBy(fn) : this.clearFilter();
1426     },
1427
1428     /**
1429      * Filter by a function. The specified function will be called for each
1430      * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1431      * otherwise it is filtered out.
1432      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1433      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1434      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1435      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1436      * </ul>
1437      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1438      */
1439     filterBy : function(fn, scope){
1440         this.snapshot = this.snapshot || this.data;
1441         this.data = this.queryBy(fn, scope||this);
1442         this.fireEvent('datachanged', this);
1443     },
1444
1445     /**
1446      * Query the records by a specified property.
1447      * @param {String} field A field on your records
1448      * @param {String/RegExp} value Either a string that the field
1449      * should begin with, or a RegExp to test against the field.
1450      * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
1451      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1452      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1453      */
1454     query : function(property, value, anyMatch, caseSensitive){
1455         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1456         return fn ? this.queryBy(fn) : this.data.clone();
1457     },
1458
1459     /**
1460      * Query the cached records in this Store using a filtering function. The specified function
1461      * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1462      * included in the results.
1463      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1464      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1465      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1466      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1467      * </ul>
1468      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1469      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1470      **/
1471     queryBy : function(fn, scope){
1472         var data = this.snapshot || this.data;
1473         return data.filterBy(fn, scope||this);
1474     },
1475
1476     /**
1477      * Finds the index of the first matching Record in this store by a specific field value.
1478      * @param {String} fieldName The name of the Record field to test.
1479      * @param {String/RegExp} value Either a string that the field value
1480      * should begin with, or a RegExp to test against the field.
1481      * @param {Number} startIndex (optional) The index to start searching at
1482      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1483      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1484      * @return {Number} The matched index or -1
1485      */
1486     find : function(property, value, start, anyMatch, caseSensitive){
1487         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1488         return fn ? this.data.findIndexBy(fn, null, start) : -1;
1489     },
1490
1491     /**
1492      * Finds the index of the first matching Record in this store by a specific field value.
1493      * @param {String} fieldName The name of the Record field to test.
1494      * @param {Mixed} value The value to match the field against.
1495      * @param {Number} startIndex (optional) The index to start searching at
1496      * @return {Number} The matched index or -1
1497      */
1498     findExact: function(property, value, start){
1499         return this.data.findIndexBy(function(rec){
1500             return rec.get(property) === value;
1501         }, this, start);
1502     },
1503
1504     /**
1505      * Find the index of the first matching Record in this Store by a function.
1506      * If the function returns <tt>true</tt> it is considered a match.
1507      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1508      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1509      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1510      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1511      * </ul>
1512      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1513      * @param {Number} startIndex (optional) The index to start searching at
1514      * @return {Number} The matched index or -1
1515      */
1516     findBy : function(fn, scope, start){
1517         return this.data.findIndexBy(fn, scope, start);
1518     },
1519
1520     /**
1521      * Collects unique values for a particular dataIndex from this store.
1522      * @param {String} dataIndex The property to collect
1523      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1524      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1525      * @return {Array} An array of the unique values
1526      **/
1527     collect : function(dataIndex, allowNull, bypassFilter){
1528         var d = (bypassFilter === true && this.snapshot) ?
1529                 this.snapshot.items : this.data.items;
1530         var v, sv, r = [], l = {};
1531         for(var i = 0, len = d.length; i < len; i++){
1532             v = d[i].data[dataIndex];
1533             sv = String(v);
1534             if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
1535                 l[sv] = true;
1536                 r[r.length] = v;
1537             }
1538         }
1539         return r;
1540     },
1541
1542     /**
1543      * Revert to a view of the Record cache with no filtering applied.
1544      * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1545      * {@link #datachanged} event.
1546      */
1547     clearFilter : function(suppressEvent){
1548         if(this.isFiltered()){
1549             this.data = this.snapshot;
1550             delete this.snapshot;
1551             if(suppressEvent !== true){
1552                 this.fireEvent('datachanged', this);
1553             }
1554         }
1555     },
1556
1557     /**
1558      * Returns true if this store is currently filtered
1559      * @return {Boolean}
1560      */
1561     isFiltered : function(){
1562         return this.snapshot && this.snapshot != this.data;
1563     },
1564
1565     // private
1566     afterEdit : function(record){
1567         if(this.modified.indexOf(record) == -1){
1568             this.modified.push(record);
1569         }
1570         this.fireEvent('update', this, record, Ext.data.Record.EDIT);
1571     },
1572
1573     // private
1574     afterReject : function(record){
1575         this.modified.remove(record);
1576         this.fireEvent('update', this, record, Ext.data.Record.REJECT);
1577     },
1578
1579     // private
1580     afterCommit : function(record){
1581         this.modified.remove(record);
1582         this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
1583     },
1584
1585     /**
1586      * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
1587      * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
1588      * Ext.data.Record.COMMIT.
1589      */
1590     commitChanges : function(){
1591         var m = this.modified.slice(0);
1592         this.modified = [];
1593         for(var i = 0, len = m.length; i < len; i++){
1594             m[i].commit();
1595         }
1596     },
1597
1598     /**
1599      * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
1600      */
1601     rejectChanges : function(){
1602         var m = this.modified.slice(0);
1603         this.modified = [];
1604         for(var i = 0, len = m.length; i < len; i++){
1605             m[i].reject();
1606         }
1607         var m = this.removed.slice(0).reverse();
1608         this.removed = [];
1609         for(var i = 0, len = m.length; i < len; i++){
1610             this.insert(m[i].lastIndex||0, m[i]);
1611             m[i].reject();
1612         }
1613     },
1614
1615     // private
1616     onMetaChange : function(meta){
1617         this.recordType = this.reader.recordType;
1618         this.fields = this.recordType.prototype.fields;
1619         delete this.snapshot;
1620         if(this.reader.meta.sortInfo){
1621             this.sortInfo = this.reader.meta.sortInfo;
1622         }else if(this.sortInfo  && !this.fields.get(this.sortInfo.field)){
1623             delete this.sortInfo;
1624         }
1625         if(this.writer){
1626             this.writer.meta = this.reader.meta;
1627         }
1628         this.modified = [];
1629         this.fireEvent('metachange', this, this.reader.meta);
1630     },
1631
1632     // private
1633     findInsertIndex : function(record){
1634         this.suspendEvents();
1635         var data = this.data.clone();
1636         this.data.add(record);
1637         this.applySort();
1638         var index = this.data.indexOf(record);
1639         this.data = data;
1640         this.resumeEvents();
1641         return index;
1642     },
1643
1644     /**
1645      * Set the value for a property name in this store's {@link #baseParams}.  Usage:</p><pre><code>
1646 myStore.setBaseParam('foo', {bar:3});
1647 </code></pre>
1648      * @param {String} name Name of the property to assign
1649      * @param {Mixed} value Value to assign the <tt>name</tt>d property
1650      **/
1651     setBaseParam : function (name, value){
1652         this.baseParams = this.baseParams || {};
1653         this.baseParams[name] = value;
1654     }
1655 });
1656
1657 Ext.reg('store', Ext.data.Store);
1658
1659 /**
1660  * @class Ext.data.Store.Error
1661  * @extends Ext.Error
1662  * Store Error extension.
1663  * @param {String} name
1664  */
1665 Ext.data.Store.Error = Ext.extend(Ext.Error, {
1666     name: 'Ext.data.Store'
1667 });
1668 Ext.apply(Ext.data.Store.Error.prototype, {
1669     lang: {
1670         'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'
1671     }
1672 });