Roo/form/Select.js
[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      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
184      */
185     blockFocus : false,
186     
187     /**
188      * @cfg {Boolean} disableClear Disable showing of clear button.
189      */
190     disableClear : false,
191     /**
192      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
193      */
194     alwaysQuery : false,
195     
196     //private
197     addicon : false,
198     editicon: false,
199     
200     // element that contains real text value.. (when hidden is used..)
201      
202     // private
203     onRender : function(ct, position){
204         Roo.form.Field.prototype.onRender.call(this, ct, position);
205         
206         if(this.store){
207             this.store.on('beforeload', this.onBeforeLoad, this);
208             this.store.on('load', this.onLoad, this);
209             this.store.on('loadexception', this.onLoadException, this);
210             this.store.load({});
211         }
212         
213         
214         
215     },
216
217     // private
218     initEvents : function(){
219         //Roo.form.ComboBox.superclass.initEvents.call(this);
220  
221     },
222
223     onDestroy : function(){
224        
225         if(this.store){
226             this.store.un('beforeload', this.onBeforeLoad, this);
227             this.store.un('load', this.onLoad, this);
228             this.store.un('loadexception', this.onLoadException, this);
229         }
230         //Roo.form.ComboBox.superclass.onDestroy.call(this);
231     },
232
233     // private
234     fireKey : function(e){
235         if(e.isNavKeyPress() && !this.list.isVisible()){
236             this.fireEvent("specialkey", this, e);
237         }
238     },
239
240     // private
241     onResize: function(w, h){
242         
243         return; 
244     
245         
246     },
247
248     /**
249      * Allow or prevent the user from directly editing the field text.  If false is passed,
250      * the user will only be able to select from the items defined in the dropdown list.  This method
251      * is the runtime equivalent of setting the 'editable' config option at config time.
252      * @param {Boolean} value True to allow the user to directly edit the field text
253      */
254     setEditable : function(value){
255          
256     },
257
258     // private
259     onBeforeLoad : function(){
260         
261         Roo.log("Select before load");
262         return;
263     
264         this.innerList.update(this.loadingText ?
265                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
266         //this.restrictHeight();
267         this.selectedIndex = -1;
268     },
269
270     // private
271     onLoad : function(){
272
273     
274         var dom = this.el.dom;
275         dom.innerHTML = '';
276          var od = dom.ownerDocument;
277          
278         if (this.emptyText) {
279             var op = od.createElement('option');
280             op.setAttribute('value', '');
281             op.innerHTML = String.format('{0}', this.emptyText);
282             dom.appendChild(op);
283         }
284         if(this.store.getCount() > 0){
285            
286             var vf = this.valueField;
287             var df = this.displayField;
288             this.store.data.each(function(r) {
289                 // which colmsn to use... testing - cdoe / title..
290                 var op = od.createElement('option');
291                 op.setAttribute('value', r.data[vf]);
292                 op.innerHTML = String.format('{0}', r.data[df]);
293                 dom.appendChild(op);
294             });
295             if (typeof(this.defaultValue != 'undefined')) {
296                 this.setValue(this.defaultValue);
297             }
298             
299              
300         }else{
301             //this.onEmptyResults();
302         }
303         //this.el.focus();
304     },
305     // private
306     onLoadException : function()
307     {
308         dom.innerHTML = '';
309             
310         Roo.log("Select on load exception");
311         return;
312     
313         this.collapse();
314         Roo.log(this.store.reader.jsonData);
315         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
316             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
317         }
318         
319         
320     },
321     // private
322     onTypeAhead : function(){
323          
324     },
325
326     // private
327     onSelect : function(record, index){
328         Roo.log('on select?');
329         return;
330         if(this.fireEvent('beforeselect', this, record, index) !== false){
331             this.setFromData(index > -1 ? record.data : false);
332             this.collapse();
333             this.fireEvent('select', this, record, index);
334         }
335     },
336
337     /**
338      * Returns the currently selected field value or empty string if no value is set.
339      * @return {String} value The selected value
340      */
341     getValue : function(){
342         var dom = this.el.dom;
343         this.value = dom.options[dom.selectedIndex].value;
344         return this.value;
345         
346     },
347
348     /**
349      * Clears any text/value currently set in the field
350      */
351     clearValue : function(){
352         this.value = '';
353         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
354         
355     },
356
357     /**
358      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
359      * will be displayed in the field.  If the value does not match the data value of an existing item,
360      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
361      * Otherwise the field will be blank (although the value will still be set).
362      * @param {String} value The value to match
363      */
364     setValue : function(v){
365         var d = this.el.dom;
366         for (var i =0; i < d.options.length;i++) {
367             if (v == d.options[i].value) {
368                 d.selectedIndex = i;
369                 this.value = v;
370                 return;
371             }
372         }
373         this.clearValue();
374     },
375     /**
376      * @property {Object} the last set data for the element
377      */
378     
379     lastData : false,
380     /**
381      * Sets the value of the field based on a object which is related to the record format for the store.
382      * @param {Object} value the value to set as. or false on reset?
383      */
384     setFromData : function(o){
385         Roo.log('setfrom data?');
386          
387         
388         
389     },
390     // private
391     reset : function(){
392         this.clearValue();
393     },
394     // private
395     findRecord : function(prop, value){
396         
397         return false;
398     
399         var record;
400         if(this.store.getCount() > 0){
401             this.store.each(function(r){
402                 if(r.data[prop] == value){
403                     record = r;
404                     return false;
405                 }
406                 return true;
407             });
408         }
409         return record;
410     },
411     
412     getName: function()
413     {
414         // returns hidden if it's set..
415         if (!this.rendered) {return ''};
416         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
417         
418     },
419      
420
421     
422
423     // private
424     onEmptyResults : function(){
425         Roo.log('empty results');
426         //this.collapse();
427     },
428
429     /**
430      * Returns true if the dropdown list is expanded, else false.
431      */
432     isExpanded : function(){
433         return false;
434     },
435
436     /**
437      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
438      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
439      * @param {String} value The data value of the item to select
440      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
441      * selected item if it is not currently in view (defaults to true)
442      * @return {Boolean} True if the value matched an item in the list, else false
443      */
444     selectByValue : function(v, scrollIntoView){
445         Roo.log('select By Value');
446         return false;
447     
448         if(v !== undefined && v !== null){
449             var r = this.findRecord(this.valueField || this.displayField, v);
450             if(r){
451                 this.select(this.store.indexOf(r), scrollIntoView);
452                 return true;
453             }
454         }
455         return false;
456     },
457
458     /**
459      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
460      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
461      * @param {Number} index The zero-based index of the list item to select
462      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
463      * selected item if it is not currently in view (defaults to true)
464      */
465     select : function(index, scrollIntoView){
466         Roo.log('select ');
467         return  ;
468         
469         this.selectedIndex = index;
470         this.view.select(index);
471         if(scrollIntoView !== false){
472             var el = this.view.getNode(index);
473             if(el){
474                 this.innerList.scrollChildIntoView(el, false);
475             }
476         }
477     },
478
479       
480
481     // private
482     validateBlur : function(){
483         
484         return;
485         
486     },
487
488     // private
489     initQuery : function(){
490         this.doQuery(this.getRawValue());
491     },
492
493     // private
494     doForce : function(){
495         if(this.el.dom.value.length > 0){
496             this.el.dom.value =
497                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
498              
499         }
500     },
501
502     /**
503      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
504      * query allowing the query action to be canceled if needed.
505      * @param {String} query The SQL query to execute
506      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
507      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
508      * saved in the current store (defaults to false)
509      */
510     doQuery : function(q, forceAll){
511         
512         Roo.log('doQuery?');
513         if(q === undefined || q === null){
514             q = '';
515         }
516         var qe = {
517             query: q,
518             forceAll: forceAll,
519             combo: this,
520             cancel:false
521         };
522         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
523             return false;
524         }
525         q = qe.query;
526         forceAll = qe.forceAll;
527         if(forceAll === true || (q.length >= this.minChars)){
528             if(this.lastQuery != q || this.alwaysQuery){
529                 this.lastQuery = q;
530                 if(this.mode == 'local'){
531                     this.selectedIndex = -1;
532                     if(forceAll){
533                         this.store.clearFilter();
534                     }else{
535                         this.store.filter(this.displayField, q);
536                     }
537                     this.onLoad();
538                 }else{
539                     this.store.baseParams[this.queryParam] = q;
540                     this.store.load({
541                         params: this.getParams(q)
542                     });
543                     this.expand();
544                 }
545             }else{
546                 this.selectedIndex = -1;
547                 this.onLoad();   
548             }
549         }
550     },
551
552     // private
553     getParams : function(q){
554         var p = {};
555         //p[this.queryParam] = q;
556         if(this.pageSize){
557             p.start = 0;
558             p.limit = this.pageSize;
559         }
560         return p;
561     },
562
563     /**
564      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
565      */
566     collapse : function(){
567         
568     },
569
570     // private
571     collapseIf : function(e){
572         
573     },
574
575     /**
576      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
577      */
578     expand : function(){
579         
580     } ,
581
582     // private
583      
584
585     /** 
586     * @cfg {Boolean} grow 
587     * @hide 
588     */
589     /** 
590     * @cfg {Number} growMin 
591     * @hide 
592     */
593     /** 
594     * @cfg {Number} growMax 
595     * @hide 
596     */
597     /**
598      * @hide
599      * @method autoSize
600      */
601     
602     setWidth : function()
603     {
604         
605     },
606     getResizeEl : function(){
607         return this.el;
608     },
609 });