Roo/form/ComboBoxArray.js
[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             // show a message if no listener is registered.
382             if (!this.hasListener('loadexception') && typeof(this.reader.jsonData.errorMsg) != 'undefined') {
383                     Roo.MessageBox.alert("Error loading",this.reader.jsonData.errorMsg);
384             }
385             // loadmask wil be hooked into this..
386             this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
387             return;
388         }
389         var r = o.records, t = o.totalRecords || r.length;
390         if(!options || options.add !== true){
391             if(this.pruneModifiedRecords){
392                 this.modified = [];
393             }
394             for(var i = 0, len = r.length; i < len; i++){
395                 r[i].join(this);
396             }
397             if(this.snapshot){
398                 this.data = this.snapshot;
399                 delete this.snapshot;
400             }
401             this.data.clear();
402             this.data.addAll(r);
403             this.totalLength = t;
404             this.applySort();
405             this.fireEvent("datachanged", this);
406         }else{
407             this.totalLength = Math.max(t, this.data.length+r.length);
408             this.add(r);
409         }
410         this.fireEvent("load", this, r, options);
411         if(options.callback){
412             options.callback.call(options.scope || this, r, options, true);
413         }
414     },
415
416
417     /**
418      * Loads data from a passed data block. A Reader which understands the format of the data
419      * must have been configured in the constructor.
420      * @param {Object} data The data block from which to read the Records.  The format of the data expected
421      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
422      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
423      */
424     loadData : function(o, append){
425         var r = this.reader.readRecords(o);
426         this.loadRecords(r, {add: append}, true);
427     },
428
429     /**
430      * Gets the number of cached records.
431      * <p>
432      * <em>If using paging, this may not be the total size of the dataset. If the data object
433      * used by the Reader contains the dataset size, then the getTotalCount() function returns
434      * the data set size</em>
435      */
436     getCount : function(){
437         return this.data.length || 0;
438     },
439
440     /**
441      * Gets the total number of records in the dataset as returned by the server.
442      * <p>
443      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
444      * the dataset size</em>
445      */
446     getTotalCount : function(){
447         return this.totalLength || 0;
448     },
449
450     /**
451      * Returns the sort state of the Store as an object with two properties:
452      * <pre><code>
453  field {String} The name of the field by which the Records are sorted
454  direction {String} The sort order, "ASC" or "DESC"
455      * </code></pre>
456      */
457     getSortState : function(){
458         return this.sortInfo;
459     },
460
461     // private
462     applySort : function(){
463         if(this.sortInfo && !this.remoteSort){
464             var s = this.sortInfo, f = s.field;
465             var st = this.fields.get(f).sortType;
466             var fn = function(r1, r2){
467                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
468                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
469             };
470             this.data.sort(s.direction, fn);
471             if(this.snapshot && this.snapshot != this.data){
472                 this.snapshot.sort(s.direction, fn);
473             }
474         }
475     },
476
477     /**
478      * Sets the default sort column and order to be used by the next load operation.
479      * @param {String} fieldName The name of the field to sort by.
480      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
481      */
482     setDefaultSort : function(field, dir){
483         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
484     },
485
486     /**
487      * Sort the Records.
488      * If remote sorting is used, the sort is performed on the server, and the cache is
489      * reloaded. If local sorting is used, the cache is sorted internally.
490      * @param {String} fieldName The name of the field to sort by.
491      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
492      */
493     sort : function(fieldName, dir){
494         var f = this.fields.get(fieldName);
495         if(!dir){
496             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
497             
498             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
499                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
500             }else{
501                 dir = f.sortDir;
502             }
503         }
504         this.sortToggle[f.name] = dir;
505         this.sortInfo = {field: f.name, direction: dir};
506         if(!this.remoteSort){
507             this.applySort();
508             this.fireEvent("datachanged", this);
509         }else{
510             this.load(this.lastOptions);
511         }
512     },
513
514     /**
515      * Calls the specified function for each of the Records in the cache.
516      * @param {Function} fn The function to call. The Record is passed as the first parameter.
517      * Returning <em>false</em> aborts and exits the iteration.
518      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
519      */
520     each : function(fn, scope){
521         this.data.each(fn, scope);
522     },
523
524     /**
525      * Gets all records modified since the last commit.  Modified records are persisted across load operations
526      * (e.g., during paging).
527      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
528      */
529     getModifiedRecords : function(){
530         return this.modified;
531     },
532
533     // private
534     createFilterFn : function(property, value, anyMatch){
535         if(!value.exec){ // not a regex
536             value = String(value);
537             if(value.length == 0){
538                 return false;
539             }
540             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
541         }
542         return function(r){
543             return value.test(r.data[property]);
544         };
545     },
546
547     /**
548      * Sums the value of <i>property</i> for each record between start and end and returns the result.
549      * @param {String} property A field on your records
550      * @param {Number} start The record index to start at (defaults to 0)
551      * @param {Number} end The last record index to include (defaults to length - 1)
552      * @return {Number} The sum
553      */
554     sum : function(property, start, end){
555         var rs = this.data.items, v = 0;
556         start = start || 0;
557         end = (end || end === 0) ? end : rs.length-1;
558
559         for(var i = start; i <= end; i++){
560             v += (rs[i].data[property] || 0);
561         }
562         return v;
563     },
564
565     /**
566      * Filter the records by a specified property.
567      * @param {String} field A field on your records
568      * @param {String/RegExp} value Either a string that the field
569      * should start with or a RegExp to test against the field
570      * @param {Boolean} anyMatch True to match any part not just the beginning
571      */
572     filter : function(property, value, anyMatch){
573         var fn = this.createFilterFn(property, value, anyMatch);
574         return fn ? this.filterBy(fn) : this.clearFilter();
575     },
576
577     /**
578      * Filter by a function. The specified function will be called with each
579      * record in this data source. If the function returns true the record is included,
580      * otherwise it is filtered.
581      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
582      * @param {Object} scope (optional) The scope of the function (defaults to this)
583      */
584     filterBy : function(fn, scope){
585         this.snapshot = this.snapshot || this.data;
586         this.data = this.queryBy(fn, scope||this);
587         this.fireEvent("datachanged", this);
588     },
589
590     /**
591      * Query the records by a specified property.
592      * @param {String} field A field on your records
593      * @param {String/RegExp} value Either a string that the field
594      * should start with or a RegExp to test against the field
595      * @param {Boolean} anyMatch True to match any part not just the beginning
596      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
597      */
598     query : function(property, value, anyMatch){
599         var fn = this.createFilterFn(property, value, anyMatch);
600         return fn ? this.queryBy(fn) : this.data.clone();
601     },
602
603     /**
604      * Query by a function. The specified function will be called with each
605      * record in this data source. If the function returns true the record is included
606      * in the results.
607      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
608      * @param {Object} scope (optional) The scope of the function (defaults to this)
609       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
610      **/
611     queryBy : function(fn, scope){
612         var data = this.snapshot || this.data;
613         return data.filterBy(fn, scope||this);
614     },
615
616     /**
617      * Collects unique values for a particular dataIndex from this store.
618      * @param {String} dataIndex The property to collect
619      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
620      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
621      * @return {Array} An array of the unique values
622      **/
623     collect : function(dataIndex, allowNull, bypassFilter){
624         var d = (bypassFilter === true && this.snapshot) ?
625                 this.snapshot.items : this.data.items;
626         var v, sv, r = [], l = {};
627         for(var i = 0, len = d.length; i < len; i++){
628             v = d[i].data[dataIndex];
629             sv = String(v);
630             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
631                 l[sv] = true;
632                 r[r.length] = v;
633             }
634         }
635         return r;
636     },
637
638     /**
639      * Revert to a view of the Record cache with no filtering applied.
640      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
641      */
642     clearFilter : function(suppressEvent){
643         if(this.snapshot && this.snapshot != this.data){
644             this.data = this.snapshot;
645             delete this.snapshot;
646             if(suppressEvent !== true){
647                 this.fireEvent("datachanged", this);
648             }
649         }
650     },
651
652     // private
653     afterEdit : function(record){
654         if(this.modified.indexOf(record) == -1){
655             this.modified.push(record);
656         }
657         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
658     },
659     
660     // private
661     afterReject : function(record){
662         this.modified.remove(record);
663         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
664     },
665
666     // private
667     afterCommit : function(record){
668         this.modified.remove(record);
669         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
670     },
671
672     /**
673      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
674      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
675      */
676     commitChanges : function(){
677         var m = this.modified.slice(0);
678         this.modified = [];
679         for(var i = 0, len = m.length; i < len; i++){
680             m[i].commit();
681         }
682     },
683
684     /**
685      * Cancel outstanding changes on all changed records.
686      */
687     rejectChanges : function(){
688         var m = this.modified.slice(0);
689         this.modified = [];
690         for(var i = 0, len = m.length; i < len; i++){
691             m[i].reject();
692         }
693     },
694
695     onMetaChange : function(meta, rtype, o){
696         this.recordType = rtype;
697         this.fields = rtype.prototype.fields;
698         delete this.snapshot;
699         this.sortInfo = meta.sortInfo || this.sortInfo;
700         this.modified = [];
701         this.fireEvent('metachange', this, this.reader.meta);
702     }
703 });