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