Roo.data.Store @config multisort - enables multiple sort columns, based on the order...
[roojs1] / Roo / data / Store.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12
13
14 /**
15  * @class Roo.data.Store
16  * @extends Roo.util.Observable
17  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
18  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
19  * <p>
20  * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
21  * has no knowledge of the format of the data returned by the Proxy.<br>
22  * <p>
23  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24  * instances from the data object. These records are cached and made available through accessor functions.
25  * @constructor
26  * Creates a new Store.
27  * @param {Object} config A config object containing the objects needed for the Store to access data,
28  * and read the data into Records.
29  */
30 Roo.data.Store = function(config){
31     this.data = new Roo.util.MixedCollection(false);
32     this.data.getKey = function(o){
33         return o.id;
34     };
35     this.baseParams = {};
36     // private
37     this.paramNames = {
38         "start" : "start",
39         "limit" : "limit",
40         "sort" : "sort",
41         "dir" : "dir",
42         "multisort" : "_multisort"
43     };
44
45     if(config && config.data){
46         this.inlineData = config.data;
47         delete config.data;
48     }
49
50     Roo.apply(this, config);
51     
52     if(this.reader){ // reader passed
53         this.reader = Roo.factory(this.reader, Roo.data);
54         this.reader.xmodule = this.xmodule || false;
55         if(!this.recordType){
56             this.recordType = this.reader.recordType;
57         }
58         if(this.reader.onMetaChange){
59             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
60         }
61     }
62
63     if(this.recordType){
64         this.fields = this.recordType.prototype.fields;
65     }
66     this.modified = [];
67
68     this.addEvents({
69         /**
70          * @event datachanged
71          * Fires when the data cache has changed, and a widget which is using this Store
72          * as a Record cache should refresh its view.
73          * @param {Store} this
74          */
75         datachanged : true,
76         /**
77          * @event metachange
78          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
79          * @param {Store} this
80          * @param {Object} meta The JSON metadata
81          */
82         metachange : true,
83         /**
84          * @event add
85          * Fires when Records have been added to the Store
86          * @param {Store} this
87          * @param {Roo.data.Record[]} records The array of Records added
88          * @param {Number} index The index at which the record(s) were added
89          */
90         add : true,
91         /**
92          * @event remove
93          * Fires when a Record has been removed from the Store
94          * @param {Store} this
95          * @param {Roo.data.Record} record The Record that was removed
96          * @param {Number} index The index at which the record was removed
97          */
98         remove : true,
99         /**
100          * @event update
101          * Fires when a Record has been updated
102          * @param {Store} this
103          * @param {Roo.data.Record} record The Record that was updated
104          * @param {String} operation The update operation being performed.  Value may be one of:
105          * <pre><code>
106  Roo.data.Record.EDIT
107  Roo.data.Record.REJECT
108  Roo.data.Record.COMMIT
109          * </code></pre>
110          */
111         update : true,
112         /**
113          * @event clear
114          * Fires when the data cache has been cleared.
115          * @param {Store} this
116          */
117         clear : true,
118         /**
119          * @event beforeload
120          * Fires before a request is made for a new data object.  If the beforeload handler returns false
121          * the load action will be canceled.
122          * @param {Store} this
123          * @param {Object} options The loading options that were specified (see {@link #load} for details)
124          */
125         beforeload : true,
126         /**
127          * @event load
128          * Fires after a new set of Records has been loaded.
129          * @param {Store} this
130          * @param {Roo.data.Record[]} records The Records that were loaded
131          * @param {Object} options The loading options that were specified (see {@link #load} for details)
132          */
133         load : true,
134         /**
135          * @event loadexception
136          * Fires if an exception occurs in the Proxy during loading.
137          * Called with the signature of the Proxy's "loadexception" event.
138          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
139          * 
140          * @param {Proxy} 
141          * @param {Object} return from JsonData.reader() - success, totalRecords, records
142          * @param {Object} load options 
143          * @param {Object} jsonData from your request (normally this contains the Exception)
144          */
145         loadexception : true
146     });
147     
148     if(this.proxy){
149         this.proxy = Roo.factory(this.proxy, Roo.data);
150         this.proxy.xmodule = this.xmodule || false;
151         this.relayEvents(this.proxy,  ["loadexception"]);
152     }
153     this.sortToggle = {};
154     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
155
156     Roo.data.Store.superclass.constructor.call(this);
157
158     if(this.inlineData){
159         this.loadData(this.inlineData);
160         delete this.inlineData;
161     }
162 };
163 Roo.extend(Roo.data.Store, Roo.util.Observable, {
164      /**
165     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
166     * without a remote query - used by combo/forms at present.
167     */
168     
169     /**
170     * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
171     */
172     /**
173     * @cfg {Array} data Inline data to be loaded when the store is initialized.
174     */
175     /**
176     * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
177     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
178     */
179     /**
180     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
181     * on any HTTP request
182     */
183     /**
184     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
185     */
186     /**
187     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
188     */
189     multiSort: false,
190     /**
191     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
192     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
193     */
194     remoteSort : false,
195
196     /**
197     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
198      * loaded or when a record is removed. (defaults to false).
199     */
200     pruneModifiedRecords : false,
201
202     // private
203     lastOptions : null,
204
205     /**
206      * Add Records to the Store and fires the add event.
207      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
208      */
209     add : function(records){
210         records = [].concat(records);
211         for(var i = 0, len = records.length; i < len; i++){
212             records[i].join(this);
213         }
214         var index = this.data.length;
215         this.data.addAll(records);
216         this.fireEvent("add", this, records, index);
217     },
218
219     /**
220      * Remove a Record from the Store and fires the remove event.
221      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
222      */
223     remove : function(record){
224         var index = this.data.indexOf(record);
225         this.data.removeAt(index);
226         if(this.pruneModifiedRecords){
227             this.modified.remove(record);
228         }
229         this.fireEvent("remove", this, record, index);
230     },
231
232     /**
233      * Remove all Records from the Store and fires the clear event.
234      */
235     removeAll : function(){
236         this.data.clear();
237         if(this.pruneModifiedRecords){
238             this.modified = [];
239         }
240         this.fireEvent("clear", this);
241     },
242
243     /**
244      * Inserts Records to the Store at the given index and fires the add event.
245      * @param {Number} index The start index at which to insert the passed Records.
246      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
247      */
248     insert : function(index, records){
249         records = [].concat(records);
250         for(var i = 0, len = records.length; i < len; i++){
251             this.data.insert(index, records[i]);
252             records[i].join(this);
253         }
254         this.fireEvent("add", this, records, index);
255     },
256
257     /**
258      * Get the index within the cache of the passed Record.
259      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
260      * @return {Number} The index of the passed Record. Returns -1 if not found.
261      */
262     indexOf : function(record){
263         return this.data.indexOf(record);
264     },
265
266     /**
267      * Get the index within the cache of the Record with the passed id.
268      * @param {String} id The id of the Record to find.
269      * @return {Number} The index of the Record. Returns -1 if not found.
270      */
271     indexOfId : function(id){
272         return this.data.indexOfKey(id);
273     },
274
275     /**
276      * Get the Record with the specified id.
277      * @param {String} id The id of the Record to find.
278      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
279      */
280     getById : function(id){
281         return this.data.key(id);
282     },
283
284     /**
285      * Get the Record at the specified index.
286      * @param {Number} index The index of the Record to find.
287      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
288      */
289     getAt : function(index){
290         return this.data.itemAt(index);
291     },
292
293     /**
294      * Returns a range of Records between specified indices.
295      * @param {Number} startIndex (optional) The starting index (defaults to 0)
296      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
297      * @return {Roo.data.Record[]} An array of Records
298      */
299     getRange : function(start, end){
300         return this.data.getRange(start, end);
301     },
302
303     // private
304     storeOptions : function(o){
305         o = Roo.apply({}, o);
306         delete o.callback;
307         delete o.scope;
308         this.lastOptions = o;
309     },
310
311     /**
312      * Loads the Record cache from the configured Proxy using the configured Reader.
313      * <p>
314      * If using remote paging, then the first load call must specify the <em>start</em>
315      * and <em>limit</em> properties in the options.params property to establish the initial
316      * position within the dataset, and the number of Records to cache on each read from the Proxy.
317      * <p>
318      * <strong>It is important to note that for remote data sources, loading is asynchronous,
319      * and this call will return before the new data has been loaded. Perform any post-processing
320      * in a callback function, or in a "load" event handler.</strong>
321      * <p>
322      * @param {Object} options An object containing properties which control loading options:<ul>
323      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
324      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
325      * passed the following arguments:<ul>
326      * <li>r : Roo.data.Record[]</li>
327      * <li>options: Options object from the load call</li>
328      * <li>success: Boolean success indicator</li></ul></li>
329      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
330      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
331      * </ul>
332      */
333     load : function(options){
334         options = options || {};
335         if(this.fireEvent("beforeload", this, options) !== false){
336             this.storeOptions(options);
337             var p = Roo.apply(options.params || {}, this.baseParams);
338             // if meta was not loaded from remote source.. try requesting it.
339             if (!this.reader.metaFromRemote) {
340                 p._requestMeta = 1;
341             }
342             if(this.sortInfo && this.remoteSort){
343                 var pn = this.paramNames;
344                 p[pn["sort"]] = this.sortInfo.field;
345                 p[pn["dir"]] = this.sortInfo.direction;
346             }
347             if (this.multiSort) {
348                 var pn = this.paramNames;
349                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
350             }
351             
352             this.proxy.load(p, this.reader, this.loadRecords, this, options);
353         }
354     },
355
356     /**
357      * Reloads the Record cache from the configured Proxy using the configured Reader and
358      * the options from the last load operation performed.
359      * @param {Object} options (optional) An object containing properties which may override the options
360      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
361      * the most recently used options are reused).
362      */
363     reload : function(options){
364         this.load(Roo.applyIf(options||{}, this.lastOptions));
365     },
366
367     // private
368     // Called as a callback by the Reader during a load operation.
369     loadRecords : function(o, options, success){
370         if(!o || success === false){
371             if(success !== false){
372                 this.fireEvent("load", this, [], options);
373             }
374             if(options.callback){
375                 options.callback.call(options.scope || this, [], options, false);
376             }
377             return;
378         }
379         // if data returned failure - throw an exception.
380         if (o.success === false) {
381             this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
382             return;
383         }
384         var r = o.records, t = o.totalRecords || r.length;
385         if(!options || options.add !== true){
386             if(this.pruneModifiedRecords){
387                 this.modified = [];
388             }
389             for(var i = 0, len = r.length; i < len; i++){
390                 r[i].join(this);
391             }
392             if(this.snapshot){
393                 this.data = this.snapshot;
394                 delete this.snapshot;
395             }
396             this.data.clear();
397             this.data.addAll(r);
398             this.totalLength = t;
399             this.applySort();
400             this.fireEvent("datachanged", this);
401         }else{
402             this.totalLength = Math.max(t, this.data.length+r.length);
403             this.add(r);
404         }
405         this.fireEvent("load", this, r, options);
406         if(options.callback){
407             options.callback.call(options.scope || this, r, options, true);
408         }
409     },
410
411     /**
412      * Loads data from a passed data block. A Reader which understands the format of the data
413      * must have been configured in the constructor.
414      * @param {Object} data The data block from which to read the Records.  The format of the data expected
415      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
416      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
417      */
418     loadData : function(o, append){
419         var r = this.reader.readRecords(o);
420         this.loadRecords(r, {add: append}, true);
421     },
422
423     /**
424      * Gets the number of cached records.
425      * <p>
426      * <em>If using paging, this may not be the total size of the dataset. If the data object
427      * used by the Reader contains the dataset size, then the getTotalCount() function returns
428      * the data set size</em>
429      */
430     getCount : function(){
431         return this.data.length || 0;
432     },
433
434     /**
435      * Gets the total number of records in the dataset as returned by the server.
436      * <p>
437      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
438      * the dataset size</em>
439      */
440     getTotalCount : function(){
441         return this.totalLength || 0;
442     },
443
444     /**
445      * Returns the sort state of the Store as an object with two properties:
446      * <pre><code>
447  field {String} The name of the field by which the Records are sorted
448  direction {String} The sort order, "ASC" or "DESC"
449      * </code></pre>
450      */
451     getSortState : function(){
452         return this.sortInfo;
453     },
454
455     // private
456     applySort : function(){
457         if(this.sortInfo && !this.remoteSort){
458             var s = this.sortInfo, f = s.field;
459             var st = this.fields.get(f).sortType;
460             var fn = function(r1, r2){
461                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
462                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
463             };
464             this.data.sort(s.direction, fn);
465             if(this.snapshot && this.snapshot != this.data){
466                 this.snapshot.sort(s.direction, fn);
467             }
468         }
469     },
470
471     /**
472      * Sets the default sort column and order to be used by the next load operation.
473      * @param {String} fieldName The name of the field to sort by.
474      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
475      */
476     setDefaultSort : function(field, dir){
477         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
478     },
479
480     /**
481      * Sort the Records.
482      * If remote sorting is used, the sort is performed on the server, and the cache is
483      * reloaded. If local sorting is used, the cache is sorted internally.
484      * @param {String} fieldName The name of the field to sort by.
485      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
486      */
487     sort : function(fieldName, dir){
488         var f = this.fields.get(fieldName);
489         if(!dir){
490             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
491             
492             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
493                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
494             }else{
495                 dir = f.sortDir;
496             }
497         }
498         this.sortToggle[f.name] = dir;
499         this.sortInfo = {field: f.name, direction: dir};
500         if(!this.remoteSort){
501             this.applySort();
502             this.fireEvent("datachanged", this);
503         }else{
504             this.load(this.lastOptions);
505         }
506     },
507
508     /**
509      * Calls the specified function for each of the Records in the cache.
510      * @param {Function} fn The function to call. The Record is passed as the first parameter.
511      * Returning <em>false</em> aborts and exits the iteration.
512      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
513      */
514     each : function(fn, scope){
515         this.data.each(fn, scope);
516     },
517
518     /**
519      * Gets all records modified since the last commit.  Modified records are persisted across load operations
520      * (e.g., during paging).
521      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
522      */
523     getModifiedRecords : function(){
524         return this.modified;
525     },
526
527     // private
528     createFilterFn : function(property, value, anyMatch){
529         if(!value.exec){ // not a regex
530             value = String(value);
531             if(value.length == 0){
532                 return false;
533             }
534             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
535         }
536         return function(r){
537             return value.test(r.data[property]);
538         };
539     },
540
541     /**
542      * Sums the value of <i>property</i> for each record between start and end and returns the result.
543      * @param {String} property A field on your records
544      * @param {Number} start The record index to start at (defaults to 0)
545      * @param {Number} end The last record index to include (defaults to length - 1)
546      * @return {Number} The sum
547      */
548     sum : function(property, start, end){
549         var rs = this.data.items, v = 0;
550         start = start || 0;
551         end = (end || end === 0) ? end : rs.length-1;
552
553         for(var i = start; i <= end; i++){
554             v += (rs[i].data[property] || 0);
555         }
556         return v;
557     },
558
559     /**
560      * Filter the records by a specified property.
561      * @param {String} field A field on your records
562      * @param {String/RegExp} value Either a string that the field
563      * should start with or a RegExp to test against the field
564      * @param {Boolean} anyMatch True to match any part not just the beginning
565      */
566     filter : function(property, value, anyMatch){
567         var fn = this.createFilterFn(property, value, anyMatch);
568         return fn ? this.filterBy(fn) : this.clearFilter();
569     },
570
571     /**
572      * Filter by a function. The specified function will be called with each
573      * record in this data source. If the function returns true the record is included,
574      * otherwise it is filtered.
575      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
576      * @param {Object} scope (optional) The scope of the function (defaults to this)
577      */
578     filterBy : function(fn, scope){
579         this.snapshot = this.snapshot || this.data;
580         this.data = this.queryBy(fn, scope||this);
581         this.fireEvent("datachanged", this);
582     },
583
584     /**
585      * Query the records by a specified property.
586      * @param {String} field A field on your records
587      * @param {String/RegExp} value Either a string that the field
588      * should start with or a RegExp to test against the field
589      * @param {Boolean} anyMatch True to match any part not just the beginning
590      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
591      */
592     query : function(property, value, anyMatch){
593         var fn = this.createFilterFn(property, value, anyMatch);
594         return fn ? this.queryBy(fn) : this.data.clone();
595     },
596
597     /**
598      * Query by a function. The specified function will be called with each
599      * record in this data source. If the function returns true the record is included
600      * in the results.
601      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
602      * @param {Object} scope (optional) The scope of the function (defaults to this)
603       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
604      **/
605     queryBy : function(fn, scope){
606         var data = this.snapshot || this.data;
607         return data.filterBy(fn, scope||this);
608     },
609
610     /**
611      * Collects unique values for a particular dataIndex from this store.
612      * @param {String} dataIndex The property to collect
613      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
614      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
615      * @return {Array} An array of the unique values
616      **/
617     collect : function(dataIndex, allowNull, bypassFilter){
618         var d = (bypassFilter === true && this.snapshot) ?
619                 this.snapshot.items : this.data.items;
620         var v, sv, r = [], l = {};
621         for(var i = 0, len = d.length; i < len; i++){
622             v = d[i].data[dataIndex];
623             sv = String(v);
624             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
625                 l[sv] = true;
626                 r[r.length] = v;
627             }
628         }
629         return r;
630     },
631
632     /**
633      * Revert to a view of the Record cache with no filtering applied.
634      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
635      */
636     clearFilter : function(suppressEvent){
637         if(this.snapshot && this.snapshot != this.data){
638             this.data = this.snapshot;
639             delete this.snapshot;
640             if(suppressEvent !== true){
641                 this.fireEvent("datachanged", this);
642             }
643         }
644     },
645
646     // private
647     afterEdit : function(record){
648         if(this.modified.indexOf(record) == -1){
649             this.modified.push(record);
650         }
651         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
652     },
653
654     // private
655     afterReject : function(record){
656         this.modified.remove(record);
657         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
658     },
659
660     // private
661     afterCommit : function(record){
662         this.modified.remove(record);
663         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
664     },
665
666     /**
667      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
668      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
669      */
670     commitChanges : function(){
671         var m = this.modified.slice(0);
672         this.modified = [];
673         for(var i = 0, len = m.length; i < len; i++){
674             m[i].commit();
675         }
676     },
677
678     /**
679      * Cancel outstanding changes on all changed records.
680      */
681     rejectChanges : function(){
682         var m = this.modified.slice(0);
683         this.modified = [];
684         for(var i = 0, len = m.length; i < len; i++){
685             m[i].reject();
686         }
687     },
688
689     onMetaChange : function(meta, rtype, o){
690         this.recordType = rtype;
691         this.fields = rtype.prototype.fields;
692         delete this.snapshot;
693         this.sortInfo = meta.sortInfo || this.sortInfo;
694         this.modified = [];
695         this.fireEvent('metachange', this, this.reader.meta);
696     }
697 });