allow string based values for comboboxarray
[roojs1] / Roo / form / Select.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  * @class Roo.form.ComboBox
15  * @extends Roo.form.TriggerField
16  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
17  * @constructor
18  * Create a new ComboBox.
19  * @param {Object} config Configuration options
20  */
21 Roo.form.Select = function(config){
22     Roo.form.Select.superclass.constructor.call(this, config);
23      
24 };
25
26 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
27     /**
28      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
29      */
30     /**
31      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
32      * rendering into an Roo.Editor, defaults to false)
33      */
34     /**
35      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
36      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
37      */
38     /**
39      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
40      */
41     /**
42      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
43      * the dropdown list (defaults to undefined, with no header element)
44      */
45
46      /**
47      * @cfg {String/Roo.Template} tpl The template to use to render the output
48      */
49      
50     // private
51     defaultAutoCreate : {tag: "select"  },
52     /**
53      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
54      */
55     listWidth: undefined,
56     /**
57      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
58      * mode = 'remote' or 'text' if mode = 'local')
59      */
60     displayField: undefined,
61     /**
62      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
63      * mode = 'remote' or 'value' if mode = 'local'). 
64      * Note: use of a valueField requires the user make a selection
65      * in order for a value to be mapped.
66      */
67     valueField: undefined,
68     
69     
70     /**
71      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
72      * field's data value (defaults to the underlying DOM element's name)
73      */
74     hiddenName: undefined,
75     /**
76      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
77      */
78     listClass: '',
79     /**
80      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
81      */
82     selectedClass: 'x-combo-selected',
83     /**
84      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
85      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
86      * which displays a downward arrow icon).
87      */
88     triggerClass : 'x-form-arrow-trigger',
89     /**
90      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
91      */
92     shadow:'sides',
93     /**
94      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
95      * anchor positions (defaults to 'tl-bl')
96      */
97     listAlign: 'tl-bl?',
98     /**
99      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
100      */
101     maxHeight: 300,
102     /**
103      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
104      * query specified by the allQuery config option (defaults to 'query')
105      */
106     triggerAction: 'query',
107     /**
108      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
109      * (defaults to 4, does not apply if editable = false)
110      */
111     minChars : 4,
112     /**
113      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
114      * delay (typeAheadDelay) if it matches a known value (defaults to false)
115      */
116     typeAhead: false,
117     /**
118      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
119      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
120      */
121     queryDelay: 500,
122     /**
123      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
124      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
125      */
126     pageSize: 0,
127     /**
128      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
129      * when editable = true (defaults to false)
130      */
131     selectOnFocus:false,
132     /**
133      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
134      */
135     queryParam: 'query',
136     /**
137      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
138      * when mode = 'remote' (defaults to 'Loading...')
139      */
140     loadingText: 'Loading...',
141     /**
142      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
143      */
144     resizable: false,
145     /**
146      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
147      */
148     handleHeight : 8,
149     /**
150      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
151      * traditional select (defaults to true)
152      */
153     editable: true,
154     /**
155      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
156      */
157     allQuery: '',
158     /**
159      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
160      */
161     mode: 'remote',
162     /**
163      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
164      * listWidth has a higher value)
165      */
166     minListWidth : 70,
167     /**
168      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
169      * allow the user to set arbitrary text into the field (defaults to false)
170      */
171     forceSelection:false,
172     /**
173      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
174      * if typeAhead = true (defaults to 250)
175      */
176     typeAheadDelay : 250,
177     /**
178      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
179      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
180      */
181     valueNotFoundText : undefined,
182     
183     /**
184      * @cfg {String} defaultValue The value displayed after loading the store.
185      */
186     defaultValue: '',
187     
188     /**
189      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
190      */
191     blockFocus : false,
192     
193     /**
194      * @cfg {Boolean} disableClear Disable showing of clear button.
195      */
196     disableClear : false,
197     /**
198      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
199      */
200     alwaysQuery : false,
201     
202     //private
203     addicon : false,
204     editicon: false,
205     
206     // element that contains real text value.. (when hidden is used..)
207      
208     // private
209     onRender : function(ct, position){
210         Roo.form.Field.prototype.onRender.call(this, ct, position);
211         
212         if(this.store){
213             this.store.on('beforeload', this.onBeforeLoad, this);
214             this.store.on('load', this.onLoad, this);
215             this.store.on('loadexception', this.onLoadException, this);
216             this.store.load({});
217         }
218         
219         
220         
221     },
222
223     // private
224     initEvents : function(){
225         //Roo.form.ComboBox.superclass.initEvents.call(this);
226  
227     },
228
229     onDestroy : function(){
230        
231         if(this.store){
232             this.store.un('beforeload', this.onBeforeLoad, this);
233             this.store.un('load', this.onLoad, this);
234             this.store.un('loadexception', this.onLoadException, this);
235         }
236         //Roo.form.ComboBox.superclass.onDestroy.call(this);
237     },
238
239     // private
240     fireKey : function(e){
241         if(e.isNavKeyPress() && !this.list.isVisible()){
242             this.fireEvent("specialkey", this, e);
243         }
244     },
245
246     // private
247     onResize: function(w, h){
248         
249         return; 
250     
251         
252     },
253
254     /**
255      * Allow or prevent the user from directly editing the field text.  If false is passed,
256      * the user will only be able to select from the items defined in the dropdown list.  This method
257      * is the runtime equivalent of setting the 'editable' config option at config time.
258      * @param {Boolean} value True to allow the user to directly edit the field text
259      */
260     setEditable : function(value){
261          
262     },
263
264     // private
265     onBeforeLoad : function(){
266         
267         Roo.log("Select before load");
268         return;
269     
270         this.innerList.update(this.loadingText ?
271                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
272         //this.restrictHeight();
273         this.selectedIndex = -1;
274     },
275
276     // private
277     onLoad : function(){
278
279     
280         var dom = this.el.dom;
281         dom.innerHTML = '';
282          var od = dom.ownerDocument;
283          
284         if (this.emptyText) {
285             var op = od.createElement('option');
286             op.setAttribute('value', '');
287             op.innerHTML = String.format('{0}', this.emptyText);
288             dom.appendChild(op);
289         }
290         if(this.store.getCount() > 0){
291            
292             var vf = this.valueField;
293             var df = this.displayField;
294             this.store.data.each(function(r) {
295                 // which colmsn to use... testing - cdoe / title..
296                 var op = od.createElement('option');
297                 op.setAttribute('value', r.data[vf]);
298                 op.innerHTML = String.format('{0}', r.data[df]);
299                 dom.appendChild(op);
300             });
301             if (typeof(this.defaultValue != 'undefined')) {
302                 this.setValue(this.defaultValue);
303             }
304             
305              
306         }else{
307             //this.onEmptyResults();
308         }
309         //this.el.focus();
310     },
311     // private
312     onLoadException : function()
313     {
314         dom.innerHTML = '';
315             
316         Roo.log("Select on load exception");
317         return;
318     
319         this.collapse();
320         Roo.log(this.store.reader.jsonData);
321         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
322             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
323         }
324         
325         
326     },
327     // private
328     onTypeAhead : function(){
329          
330     },
331
332     // private
333     onSelect : function(record, index){
334         Roo.log('on select?');
335         return;
336         if(this.fireEvent('beforeselect', this, record, index) !== false){
337             this.setFromData(index > -1 ? record.data : false);
338             this.collapse();
339             this.fireEvent('select', this, record, index);
340         }
341     },
342
343     /**
344      * Returns the currently selected field value or empty string if no value is set.
345      * @return {String} value The selected value
346      */
347     getValue : function(){
348         var dom = this.el.dom;
349         this.value = dom.options[dom.selectedIndex].value;
350         return this.value;
351         
352     },
353
354     /**
355      * Clears any text/value currently set in the field
356      */
357     clearValue : function(){
358         this.value = '';
359         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
360         
361     },
362
363     /**
364      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
365      * will be displayed in the field.  If the value does not match the data value of an existing item,
366      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
367      * Otherwise the field will be blank (although the value will still be set).
368      * @param {String} value The value to match
369      */
370     setValue : function(v){
371         var d = this.el.dom;
372         for (var i =0; i < d.options.length;i++) {
373             if (v == d.options[i].value) {
374                 d.selectedIndex = i;
375                 this.value = v;
376                 return;
377             }
378         }
379         this.clearValue();
380     },
381     /**
382      * @property {Object} the last set data for the element
383      */
384     
385     lastData : false,
386     /**
387      * Sets the value of the field based on a object which is related to the record format for the store.
388      * @param {Object} value the value to set as. or false on reset?
389      */
390     setFromData : function(o){
391         Roo.log('setfrom data?');
392          
393         
394         
395     },
396     // private
397     reset : function(){
398         this.clearValue();
399     },
400     // private
401     findRecord : function(prop, value){
402         
403         return false;
404     
405         var record;
406         if(this.store.getCount() > 0){
407             this.store.each(function(r){
408                 if(r.data[prop] == value){
409                     record = r;
410                     return false;
411                 }
412                 return true;
413             });
414         }
415         return record;
416     },
417     
418     getName: function()
419     {
420         // returns hidden if it's set..
421         if (!this.rendered) {return ''};
422         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
423         
424     },
425      
426
427     
428
429     // private
430     onEmptyResults : function(){
431         Roo.log('empty results');
432         //this.collapse();
433     },
434
435     /**
436      * Returns true if the dropdown list is expanded, else false.
437      */
438     isExpanded : function(){
439         return false;
440     },
441
442     /**
443      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
444      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
445      * @param {String} value The data value of the item to select
446      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
447      * selected item if it is not currently in view (defaults to true)
448      * @return {Boolean} True if the value matched an item in the list, else false
449      */
450     selectByValue : function(v, scrollIntoView){
451         Roo.log('select By Value');
452         return false;
453     
454         if(v !== undefined && v !== null){
455             var r = this.findRecord(this.valueField || this.displayField, v);
456             if(r){
457                 this.select(this.store.indexOf(r), scrollIntoView);
458                 return true;
459             }
460         }
461         return false;
462     },
463
464     /**
465      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
466      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
467      * @param {Number} index The zero-based index of the list item to select
468      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
469      * selected item if it is not currently in view (defaults to true)
470      */
471     select : function(index, scrollIntoView){
472         Roo.log('select ');
473         return  ;
474         
475         this.selectedIndex = index;
476         this.view.select(index);
477         if(scrollIntoView !== false){
478             var el = this.view.getNode(index);
479             if(el){
480                 this.innerList.scrollChildIntoView(el, false);
481             }
482         }
483     },
484
485       
486
487     // private
488     validateBlur : function(){
489         
490         return;
491         
492     },
493
494     // private
495     initQuery : function(){
496         this.doQuery(this.getRawValue());
497     },
498
499     // private
500     doForce : function(){
501         if(this.el.dom.value.length > 0){
502             this.el.dom.value =
503                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
504              
505         }
506     },
507
508     /**
509      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
510      * query allowing the query action to be canceled if needed.
511      * @param {String} query The SQL query to execute
512      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
513      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
514      * saved in the current store (defaults to false)
515      */
516     doQuery : function(q, forceAll){
517         
518         Roo.log('doQuery?');
519         if(q === undefined || q === null){
520             q = '';
521         }
522         var qe = {
523             query: q,
524             forceAll: forceAll,
525             combo: this,
526             cancel:false
527         };
528         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
529             return false;
530         }
531         q = qe.query;
532         forceAll = qe.forceAll;
533         if(forceAll === true || (q.length >= this.minChars)){
534             if(this.lastQuery != q || this.alwaysQuery){
535                 this.lastQuery = q;
536                 if(this.mode == 'local'){
537                     this.selectedIndex = -1;
538                     if(forceAll){
539                         this.store.clearFilter();
540                     }else{
541                         this.store.filter(this.displayField, q);
542                     }
543                     this.onLoad();
544                 }else{
545                     this.store.baseParams[this.queryParam] = q;
546                     this.store.load({
547                         params: this.getParams(q)
548                     });
549                     this.expand();
550                 }
551             }else{
552                 this.selectedIndex = -1;
553                 this.onLoad();   
554             }
555         }
556     },
557
558     // private
559     getParams : function(q){
560         var p = {};
561         //p[this.queryParam] = q;
562         if(this.pageSize){
563             p.start = 0;
564             p.limit = this.pageSize;
565         }
566         return p;
567     },
568
569     /**
570      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
571      */
572     collapse : function(){
573         
574     },
575
576     // private
577     collapseIf : function(e){
578         
579     },
580
581     /**
582      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
583      */
584     expand : function(){
585         
586     } ,
587
588     // private
589      
590
591     /** 
592     * @cfg {Boolean} grow 
593     * @hide 
594     */
595     /** 
596     * @cfg {Number} growMin 
597     * @hide 
598     */
599     /** 
600     * @cfg {Number} growMax 
601     * @hide 
602     */
603     /**
604      * @hide
605      * @method autoSize
606      */
607     
608     setWidth : function()
609     {
610         
611     },
612     getResizeEl : function(){
613         return this.el;
614     }
615 });