Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / widgets / form / Combo.js
1 /*!
2  * Ext JS Library 3.1.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.form.ComboBox
9  * @extends Ext.form.TriggerField
10  * <p>A combobox control with support for autocomplete, remote-loading, paging and many other features.</p>
11  * <p>A ComboBox works in a similar manner to a traditional HTML &lt;select> field. The difference is
12  * that to submit the {@link #valueField}, you must specify a {@link #hiddenName} to create a hidden input
13  * field to hold the value of the valueField. The <i>{@link #displayField}</i> is shown in the text field
14  * which is named according to the {@link #name}.</p>
15  * <p><b><u>Events</u></b></p>
16  * <p>To do something when something in ComboBox is selected, configure the select event:<pre><code>
17 var cb = new Ext.form.ComboBox({
18     // all of your config options
19     listeners:{
20          scope: yourScope,
21          'select': yourFunction
22     }
23 });
24
25 // Alternatively, you can assign events after the object is created:
26 var cb = new Ext.form.ComboBox(yourOptions);
27 cb.on('select', yourFunction, yourScope);
28  * </code></pre></p>
29  *
30  * <p><b><u>ComboBox in Grid</u></b></p>
31  * <p>If using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a {@link Ext.grid.Column#renderer renderer}
32  * will be needed to show the displayField when the editor is not active.  Set up the renderer manually, or implement
33  * a reusable render, for example:<pre><code>
34 // create reusable renderer
35 Ext.util.Format.comboRenderer = function(combo){
36     return function(value){
37         var record = combo.findRecord(combo.{@link #valueField}, value);
38         return record ? record.get(combo.{@link #displayField}) : combo.{@link #valueNotFoundText};
39     }
40 }
41
42 // create the combo instance
43 var combo = new Ext.form.ComboBox({
44     {@link #typeAhead}: true,
45     {@link #triggerAction}: 'all',
46     {@link #lazyRender}:true,
47     {@link #mode}: 'local',
48     {@link #store}: new Ext.data.ArrayStore({
49         id: 0,
50         fields: [
51             'myId',
52             'displayText'
53         ],
54         data: [[1, 'item1'], [2, 'item2']]
55     }),
56     {@link #valueField}: 'myId',
57     {@link #displayField}: 'displayText'
58 });
59
60 // snippet of column model used within grid
61 var cm = new Ext.grid.ColumnModel([{
62        ...
63     },{
64        header: "Some Header",
65        dataIndex: 'whatever',
66        width: 130,
67        editor: combo, // specify reference to combo instance
68        renderer: Ext.util.Format.comboRenderer(combo) // pass combo instance to reusable renderer
69     },
70     ...
71 ]);
72  * </code></pre></p>
73  *
74  * <p><b><u>Filtering</u></b></p>
75  * <p>A ComboBox {@link #doQuery uses filtering itself}, for information about filtering the ComboBox
76  * store manually see <tt>{@link #lastQuery}</tt>.</p>
77  * @constructor
78  * Create a new ComboBox.
79  * @param {Object} config Configuration options
80  * @xtype combo
81  */
82 Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, {
83     /**
84      * @cfg {Mixed} transform The id, DOM node or element of an existing HTML SELECT to convert to a ComboBox.
85      * Note that if you specify this and the combo is going to be in an {@link Ext.form.BasicForm} or
86      * {@link Ext.form.FormPanel}, you must also set <tt>{@link #lazyRender} = true</tt>.
87      */
88     /**
89      * @cfg {Boolean} lazyRender <tt>true</tt> to prevent the ComboBox from rendering until requested
90      * (should always be used when rendering into an {@link Ext.Editor} (e.g. {@link Ext.grid.EditorGridPanel Grids}),
91      * defaults to <tt>false</tt>).
92      */
93     /**
94      * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or <tt>true</tt> for a default
95      * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
96      * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:</p>
97      * <pre><code>{tag: "input", type: "text", size: "24", autocomplete: "off"}</code></pre>
98      */
99     /**
100      * @cfg {Ext.data.Store/Array} store The data source to which this combo is bound (defaults to <tt>undefined</tt>).
101      * Acceptable values for this property are:
102      * <div class="mdetail-params"><ul>
103      * <li><b>any {@link Ext.data.Store Store} subclass</b></li>
104      * <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally,
105      * automatically generating {@link Ext.data.Field#name field names} to work with all data components.
106      * <div class="mdetail-params"><ul>
107      * <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
108      * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo
109      * {@link #valueField} and {@link #displayField})</div></li>
110      * <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
111      * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
112      * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}.
113      * </div></li></ul></div></li></ul></div>
114      * <p>See also <tt>{@link #mode}</tt>.</p>
115      */
116     /**
117      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
118      * the dropdown list (defaults to undefined, with no header element)
119      */
120
121     // private
122     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
123     /**
124      * @cfg {Number} listWidth The width (used as a parameter to {@link Ext.Element#setWidth}) of the dropdown
125      * list (defaults to the width of the ComboBox field).  See also <tt>{@link #minListWidth}
126      */
127     /**
128      * @cfg {String} displayField The underlying {@link Ext.data.Field#name data field name} to bind to this
129      * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field1'</tt> if
130      * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
131      * the store configuration}).
132      * <p>See also <tt>{@link #valueField}</tt>.</p>
133      * <p><b>Note</b>: if using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a
134      * {@link Ext.grid.Column#renderer renderer} will be needed to show the displayField when the editor is not
135      * active.</p>
136      */
137     /**
138      * @cfg {String} valueField The underlying {@link Ext.data.Field#name data value name} to bind to this
139      * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field2'</tt> if
140      * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
141      * the store configuration}).
142      * <p><b>Note</b>: use of a <tt>valueField</tt> requires the user to make a selection in order for a value to be
143      * mapped.  See also <tt>{@link #hiddenName}</tt>, <tt>{@link #hiddenValue}</tt>, and <tt>{@link #displayField}</tt>.</p>
144      */
145     /**
146      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
147      * field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically
148      * post during a form submission.  See also {@link #valueField}.
149      * <p><b>Note</b>: the hidden field's id will also default to this name if {@link #hiddenId} is not specified.
150      * The ComboBox {@link Ext.Component#id id} and the <tt>{@link #hiddenId}</tt> <b>should be different</b>, since
151      * no two DOM nodes should share the same id.  So, if the ComboBox <tt>{@link Ext.form.Field#name name}</tt> and
152      * <tt>hiddenName</tt> are the same, you should specify a unique <tt>{@link #hiddenId}</tt>.</p>
153      */
154     /**
155      * @cfg {String} hiddenId If <tt>{@link #hiddenName}</tt> is specified, <tt>hiddenId</tt> can also be provided
156      * to give the hidden field a unique id (defaults to the <tt>{@link #hiddenName}</tt>).  The <tt>hiddenId</tt>
157      * and combo {@link Ext.Component#id id} should be different, since no two DOM
158      * nodes should share the same id.
159      */
160     /**
161      * @cfg {String} hiddenValue Sets the initial value of the hidden field if {@link #hiddenName} is
162      * specified to contain the selected {@link #valueField}, from the Store. Defaults to the configured
163      * <tt>{@link Ext.form.Field#value value}</tt>.
164      */
165     /**
166      * @cfg {String} listClass The CSS class to add to the predefined <tt>'x-combo-list'</tt> class
167      * applied the dropdown list element (defaults to '').
168      */
169     listClass : '',
170     /**
171      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list
172      * (defaults to <tt>'x-combo-selected'</tt>)
173      */
174     selectedClass : 'x-combo-selected',
175     /**
176      * @cfg {String} listEmptyText The empty text to display in the data view if no items are found.
177      * (defaults to '')
178      */
179     listEmptyText: '',
180     /**
181      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always
182      * get the class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
183      * (defaults to <tt>'x-form-arrow-trigger'</tt> which displays a downward arrow icon).
184      */
185     triggerClass : 'x-form-arrow-trigger',
186     /**
187      * @cfg {Boolean/String} shadow <tt>true</tt> or <tt>"sides"</tt> for the default effect, <tt>"frame"</tt> for
188      * 4-way shadow, and <tt>"drop"</tt> for bottom-right
189      */
190     shadow : 'sides',
191     /**
192      * @cfg {String} listAlign A valid anchor position value. See <tt>{@link Ext.Element#alignTo}</tt> for details
193      * on supported anchor positions (defaults to <tt>'tl-bl?'</tt>)
194      */
195     listAlign : 'tl-bl?',
196     /**
197      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown
198      * (defaults to <tt>300</tt>)
199      */
200     maxHeight : 300,
201     /**
202      * @cfg {Number} minHeight The minimum height in pixels of the dropdown list when the list is constrained by its
203      * distance to the viewport edges (defaults to <tt>90</tt>)
204      */
205     minHeight : 90,
206     /**
207      * @cfg {String} triggerAction The action to execute when the trigger is clicked.
208      * <div class="mdetail-params"><ul>
209      * <li><b><tt>'query'</tt></b> : <b>Default</b>
210      * <p class="sub-desc">{@link #doQuery run the query} using the {@link Ext.form.Field#getRawValue raw value}.</p></li>
211      * <li><b><tt>'all'</tt></b> :
212      * <p class="sub-desc">{@link #doQuery run the query} specified by the <tt>{@link #allQuery}</tt> config option</p></li>
213      * </ul></div>
214      * <p>See also <code>{@link #queryParam}</code>.</p>
215      */
216     triggerAction : 'query',
217     /**
218      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and
219      * {@link #typeAhead} activate (defaults to <tt>4</tt> if <tt>{@link #mode} = 'remote'</tt> or <tt>0</tt> if
220      * <tt>{@link #mode} = 'local'</tt>, does not apply if
221      * <tt>{@link Ext.form.TriggerField#editable editable} = false</tt>).
222      */
223     minChars : 4,
224     /**
225      * @cfg {Boolean} typeAhead <tt>true</tt> to populate and autoselect the remainder of the text being
226      * typed after a configurable delay ({@link #typeAheadDelay}) if it matches a known value (defaults
227      * to <tt>false</tt>)
228      */
229     typeAhead : false,
230     /**
231      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and
232      * sending the query to filter the dropdown list (defaults to <tt>500</tt> if <tt>{@link #mode} = 'remote'</tt>
233      * or <tt>10</tt> if <tt>{@link #mode} = 'local'</tt>)
234      */
235     queryDelay : 500,
236     /**
237      * @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.PagingToolbar} is displayed in the
238      * footer of the dropdown list and the {@link #doQuery filter queries} will execute with page start and
239      * {@link Ext.PagingToolbar#pageSize limit} parameters. Only applies when <tt>{@link #mode} = 'remote'</tt>
240      * (defaults to <tt>0</tt>).
241      */
242     pageSize : 0,
243     /**
244      * @cfg {Boolean} selectOnFocus <tt>true</tt> to select any existing text in the field immediately on focus.
245      * Only applies when <tt>{@link Ext.form.TriggerField#editable editable} = true</tt> (defaults to
246      * <tt>false</tt>).
247      */
248     selectOnFocus : false,
249     /**
250      * @cfg {String} queryParam Name of the query ({@link Ext.data.Store#baseParam baseParam} name for the store)
251      * as it will be passed on the querystring (defaults to <tt>'query'</tt>)
252      */
253     queryParam : 'query',
254     /**
255      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
256      * when <tt>{@link #mode} = 'remote'</tt> (defaults to <tt>'Loading...'</tt>)
257      */
258     loadingText : 'Loading...',
259     /**
260      * @cfg {Boolean} resizable <tt>true</tt> to add a resize handle to the bottom of the dropdown list
261      * (creates an {@link Ext.Resizable} with 'se' {@link Ext.Resizable#pinned pinned} handles).
262      * Defaults to <tt>false</tt>.
263      */
264     resizable : false,
265     /**
266      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if
267      * <tt>{@link #resizable} = true</tt> (defaults to <tt>8</tt>)
268      */
269     handleHeight : 8,
270     /**
271      * @cfg {String} allQuery The text query to send to the server to return all records for the list
272      * with no filtering (defaults to '')
273      */
274     allQuery: '',
275     /**
276      * @cfg {String} mode Acceptable values are:
277      * <div class="mdetail-params"><ul>
278      * <li><b><tt>'remote'</tt></b> : <b>Default</b>
279      * <p class="sub-desc">Automatically loads the <tt>{@link #store}</tt> the <b>first</b> time the trigger
280      * is clicked. If you do not want the store to be automatically loaded the first time the trigger is
281      * clicked, set to <tt>'local'</tt> and manually load the store.  To force a requery of the store
282      * <b>every</b> time the trigger is clicked see <tt>{@link #lastQuery}</tt>.</p></li>
283      * <li><b><tt>'local'</tt></b> :
284      * <p class="sub-desc">ComboBox loads local data</p>
285      * <pre><code>
286 var combo = new Ext.form.ComboBox({
287     renderTo: document.body,
288     mode: 'local',
289     store: new Ext.data.ArrayStore({
290         id: 0,
291         fields: [
292             'myId',  // numeric value is the key
293             'displayText'
294         ],
295         data: [[1, 'item1'], [2, 'item2']]  // data is local
296     }),
297     valueField: 'myId',
298     displayField: 'displayText',
299     triggerAction: 'all'
300 });
301      * </code></pre></li>
302      * </ul></div>
303      */
304     mode: 'remote',
305     /**
306      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to <tt>70</tt>, will
307      * be ignored if <tt>{@link #listWidth}</tt> has a higher value)
308      */
309     minListWidth : 70,
310     /**
311      * @cfg {Boolean} forceSelection <tt>true</tt> to restrict the selected value to one of the values in the list,
312      * <tt>false</tt> to allow the user to set arbitrary text into the field (defaults to <tt>false</tt>)
313      */
314     forceSelection : false,
315     /**
316      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
317      * if <tt>{@link #typeAhead} = true</tt> (defaults to <tt>250</tt>)
318      */
319     typeAheadDelay : 250,
320     /**
321      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
322      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
323      * default text is used, it means there is no value set and no validation will occur on this field.
324      */
325
326     /**
327      * @cfg {Boolean} lazyInit <tt>true</tt> to not initialize the list for this combo until the field is focused
328      * (defaults to <tt>true</tt>)
329      */
330     lazyInit : true,
331
332     /**
333      * @cfg {Boolean} clearFilterOnReset <tt>true</tt> to clear any filters on the store (when in local mode) when reset is called
334      * (defaults to <tt>true</tt>)
335      */
336     clearFilterOnReset : true,
337
338     /**
339      * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
340      * If a hiddenName is specified, setting this to true will cause both the hidden field and the element to be submitted.
341      * Defaults to <tt>undefined</tt>.
342      */
343     submitValue: undefined,
344
345     /**
346      * The value of the match string used to filter the store. Delete this property to force a requery.
347      * Example use:
348      * <pre><code>
349 var combo = new Ext.form.ComboBox({
350     ...
351     mode: 'remote',
352     ...
353     listeners: {
354         // delete the previous query in the beforequery event or set
355         // combo.lastQuery = null (this will reload the store the next time it expands)
356         beforequery: function(qe){
357             delete qe.combo.lastQuery;
358         }
359     }
360 });
361      * </code></pre>
362      * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used
363      * configure the combo with <tt>lastQuery=''</tt>. Example use:
364      * <pre><code>
365 var combo = new Ext.form.ComboBox({
366     ...
367     mode: 'local',
368     triggerAction: 'all',
369     lastQuery: ''
370 });
371      * </code></pre>
372      * @property lastQuery
373      * @type String
374      */
375
376     // private
377     initComponent : function(){
378         Ext.form.ComboBox.superclass.initComponent.call(this);
379         this.addEvents(
380             /**
381              * @event expand
382              * Fires when the dropdown list is expanded
383              * @param {Ext.form.ComboBox} combo This combo box
384              */
385             'expand',
386             /**
387              * @event collapse
388              * Fires when the dropdown list is collapsed
389              * @param {Ext.form.ComboBox} combo This combo box
390              */
391             'collapse',
392             /**
393              * @event beforeselect
394              * Fires before a list item is selected. Return false to cancel the selection.
395              * @param {Ext.form.ComboBox} combo This combo box
396              * @param {Ext.data.Record} record The data record returned from the underlying store
397              * @param {Number} index The index of the selected item in the dropdown list
398              */
399             'beforeselect',
400             /**
401              * @event select
402              * Fires when a list item is selected
403              * @param {Ext.form.ComboBox} combo This combo box
404              * @param {Ext.data.Record} record The data record returned from the underlying store
405              * @param {Number} index The index of the selected item in the dropdown list
406              */
407             'select',
408             /**
409              * @event beforequery
410              * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
411              * cancel property to true.
412              * @param {Object} queryEvent An object that has these properties:<ul>
413              * <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">This combo box</div></li>
414              * <li><code>query</code> : String <div class="sub-desc">The query</div></li>
415              * <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li>
416              * <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li>
417              * </ul>
418              */
419             'beforequery'
420         );
421         if(this.transform){
422             var s = Ext.getDom(this.transform);
423             if(!this.hiddenName){
424                 this.hiddenName = s.name;
425             }
426             if(!this.store){
427                 this.mode = 'local';
428                 var d = [], opts = s.options;
429                 for(var i = 0, len = opts.length;i < len; i++){
430                     var o = opts[i],
431                         value = (o.hasAttribute ? o.hasAttribute('value') : o.getAttributeNode('value').specified) ? o.value : o.text;
432                     if(o.selected && Ext.isEmpty(this.value, true)) {
433                         this.value = value;
434                     }
435                     d.push([value, o.text]);
436                 }
437                 this.store = new Ext.data.ArrayStore({
438                     'id': 0,
439                     fields: ['value', 'text'],
440                     data : d,
441                     autoDestroy: true
442                 });
443                 this.valueField = 'value';
444                 this.displayField = 'text';
445             }
446             s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
447             if(!this.lazyRender){
448                 this.target = true;
449                 this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
450                 this.render(this.el.parentNode, s);
451             }
452             Ext.removeNode(s);
453         }
454         //auto-configure store from local array data
455         else if(this.store){
456             this.store = Ext.StoreMgr.lookup(this.store);
457             if(this.store.autoCreated){
458                 this.displayField = this.valueField = 'field1';
459                 if(!this.store.expandData){
460                     this.displayField = 'field2';
461                 }
462                 this.mode = 'local';
463             }
464         }
465
466         this.selectedIndex = -1;
467         if(this.mode == 'local'){
468             if(!Ext.isDefined(this.initialConfig.queryDelay)){
469                 this.queryDelay = 10;
470             }
471             if(!Ext.isDefined(this.initialConfig.minChars)){
472                 this.minChars = 0;
473             }
474         }
475     },
476
477     // private
478     onRender : function(ct, position){
479         if(this.hiddenName && !Ext.isDefined(this.submitValue)){
480             this.submitValue = false;
481         }
482         Ext.form.ComboBox.superclass.onRender.call(this, ct, position);
483         if(this.hiddenName){
484             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
485                     id: (this.hiddenId||this.hiddenName)}, 'before', true);
486
487         }
488         if(Ext.isGecko){
489             this.el.dom.setAttribute('autocomplete', 'off');
490         }
491
492         if(!this.lazyInit){
493             this.initList();
494         }else{
495             this.on('focus', this.initList, this, {single: true});
496         }
497     },
498
499     // private
500     initValue : function(){
501         Ext.form.ComboBox.superclass.initValue.call(this);
502         if(this.hiddenField){
503             this.hiddenField.value =
504                 Ext.isDefined(this.hiddenValue) ? this.hiddenValue :
505                 Ext.isDefined(this.value) ? this.value : '';
506         }
507     },
508
509     // private
510     initList : function(){
511         if(!this.list){
512             var cls = 'x-combo-list';
513
514             this.list = new Ext.Layer({
515                 parentEl: this.getListParent(),
516                 shadow: this.shadow,
517                 cls: [cls, this.listClass].join(' '),
518                 constrain:false,
519                 zindex: 12000
520             });
521
522             var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
523             this.list.setSize(lw, 0);
524             this.list.swallowEvent('mousewheel');
525             this.assetHeight = 0;
526             if(this.syncFont !== false){
527                 this.list.setStyle('font-size', this.el.getStyle('font-size'));
528             }
529             if(this.title){
530                 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
531                 this.assetHeight += this.header.getHeight();
532             }
533
534             this.innerList = this.list.createChild({cls:cls+'-inner'});
535             this.mon(this.innerList, 'mouseover', this.onViewOver, this);
536             this.mon(this.innerList, 'mousemove', this.onViewMove, this);
537             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
538
539             if(this.pageSize){
540                 this.footer = this.list.createChild({cls:cls+'-ft'});
541                 this.pageTb = new Ext.PagingToolbar({
542                     store: this.store,
543                     pageSize: this.pageSize,
544                     renderTo:this.footer
545                 });
546                 this.assetHeight += this.footer.getHeight();
547             }
548
549             if(!this.tpl){
550                 /**
551                 * @cfg {String/Ext.XTemplate} tpl <p>The template string, or {@link Ext.XTemplate} instance to
552                 * use to display each item in the dropdown list. The dropdown list is displayed in a
553                 * DataView. See {@link #view}.</p>
554                 * <p>The default template string is:</p><pre><code>
555                   '&lt;tpl for=".">&lt;div class="x-combo-list-item">{' + this.displayField + '}&lt;/div>&lt;/tpl>'
556                 * </code></pre>
557                 * <p>Override the default value to create custom UI layouts for items in the list.
558                 * For example:</p><pre><code>
559                   '&lt;tpl for=".">&lt;div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}&lt;/div>&lt;/tpl>'
560                 * </code></pre>
561                 * <p>The template <b>must</b> contain one or more substitution parameters using field
562                 * names from the Combo's</b> {@link #store Store}. In the example above an
563                 * <pre>ext:qtip</pre> attribute is added to display other fields from the Store.</p>
564                 * <p>To preserve the default visual look of list items, add the CSS class name
565                 * <pre>x-combo-list-item</pre> to the template's container element.</p>
566                 * <p>Also see {@link #itemSelector} for additional details.</p>
567                 */
568                 this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
569                 /**
570                  * @cfg {String} itemSelector
571                  * <p>A simple CSS selector (e.g. div.some-class or span:first-child) that will be
572                  * used to determine what nodes the {@link #view Ext.DataView} which handles the dropdown
573                  * display will be working with.</p>
574                  * <p><b>Note</b>: this setting is <b>required</b> if a custom XTemplate has been
575                  * specified in {@link #tpl} which assigns a class other than <pre>'x-combo-list-item'</pre>
576                  * to dropdown list items</b>
577                  */
578             }
579
580             /**
581             * The {@link Ext.DataView DataView} used to display the ComboBox's options.
582             * @type Ext.DataView
583             */
584             this.view = new Ext.DataView({
585                 applyTo: this.innerList,
586                 tpl: this.tpl,
587                 singleSelect: true,
588                 selectedClass: this.selectedClass,
589                 itemSelector: this.itemSelector || '.' + cls + '-item',
590                 emptyText: this.listEmptyText
591             });
592
593             this.mon(this.view, 'click', this.onViewClick, this);
594
595             this.bindStore(this.store, true);
596
597             if(this.resizable){
598                 this.resizer = new Ext.Resizable(this.list,  {
599                    pinned:true, handles:'se'
600                 });
601                 this.mon(this.resizer, 'resize', function(r, w, h){
602                     this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
603                     this.listWidth = w;
604                     this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
605                     this.restrictHeight();
606                 }, this);
607
608                 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
609             }
610         }
611     },
612
613     /**
614      * <p>Returns the element used to house this ComboBox's pop-up list. Defaults to the document body.</p>
615      * A custom implementation may be provided as a configuration option if the floating list needs to be rendered
616      * to a different Element. An example might be rendering the list inside a Menu so that clicking
617      * the list does not hide the Menu:<pre><code>
618 var store = new Ext.data.ArrayStore({
619     autoDestroy: true,
620     fields: ['initials', 'fullname'],
621     data : [
622         ['FF', 'Fred Flintstone'],
623         ['BR', 'Barney Rubble']
624     ]
625 });
626
627 var combo = new Ext.form.ComboBox({
628     store: store,
629     displayField: 'fullname',
630     emptyText: 'Select a name...',
631     forceSelection: true,
632     getListParent: function() {
633         return this.el.up('.x-menu');
634     },
635     iconCls: 'no-icon', //use iconCls if placing within menu to shift to right side of menu
636     mode: 'local',
637     selectOnFocus: true,
638     triggerAction: 'all',
639     typeAhead: true,
640     width: 135
641 });
642
643 var menu = new Ext.menu.Menu({
644     id: 'mainMenu',
645     items: [
646         combo // A Field in a Menu
647     ]
648 });
649 </code></pre>
650      */
651     getListParent : function() {
652         return document.body;
653     },
654
655     /**
656      * Returns the store associated with this combo.
657      * @return {Ext.data.Store} The store
658      */
659     getStore : function(){
660         return this.store;
661     },
662
663     // private
664     bindStore : function(store, initial){
665         if(this.store && !initial){
666             if(this.store !== store && this.store.autoDestroy){
667                 this.store.destroy();
668             }else{
669                 this.store.un('beforeload', this.onBeforeLoad, this);
670                 this.store.un('load', this.onLoad, this);
671                 this.store.un('exception', this.collapse, this);
672             }
673             if(!store){
674                 this.store = null;
675                 if(this.view){
676                     this.view.bindStore(null);
677                 }
678                 if(this.pageTb){
679                     this.pageTb.bindStore(null);
680                 }
681             }
682         }
683         if(store){
684             if(!initial) {
685                 this.lastQuery = null;
686                 if(this.pageTb) {
687                     this.pageTb.bindStore(store);
688                 }
689             }
690
691             this.store = Ext.StoreMgr.lookup(store);
692             this.store.on({
693                 scope: this,
694                 beforeload: this.onBeforeLoad,
695                 load: this.onLoad,
696                 exception: this.collapse
697             });
698
699             if(this.view){
700                 this.view.bindStore(store);
701             }
702         }
703     },
704
705     reset : function(){
706         Ext.form.ComboBox.superclass.reset.call(this);
707         if(this.clearFilterOnReset && this.mode == 'local'){
708             this.store.clearFilter();
709         }
710     },
711
712     // private
713     initEvents : function(){
714         Ext.form.ComboBox.superclass.initEvents.call(this);
715
716         this.keyNav = new Ext.KeyNav(this.el, {
717             "up" : function(e){
718                 this.inKeyMode = true;
719                 this.selectPrev();
720             },
721
722             "down" : function(e){
723                 if(!this.isExpanded()){
724                     this.onTriggerClick();
725                 }else{
726                     this.inKeyMode = true;
727                     this.selectNext();
728                 }
729             },
730
731             "enter" : function(e){
732                 this.onViewClick();
733             },
734
735             "esc" : function(e){
736                 this.collapse();
737             },
738
739             "tab" : function(e){
740                 this.onViewClick(false);
741                 return true;
742             },
743
744             scope : this,
745
746             doRelay : function(e, h, hname){
747                 if(hname == 'down' || this.scope.isExpanded()){
748                     // this MUST be called before ComboBox#fireKey()
749                     var relay = Ext.KeyNav.prototype.doRelay.apply(this, arguments);
750                     if(!Ext.isIE && Ext.EventManager.useKeydown){
751                         // call Combo#fireKey() for browsers which use keydown event (except IE)
752                         this.scope.fireKey(e);
753                     }
754                     return relay;
755                 }
756                 return true;
757             },
758
759             forceKeyDown : true,
760             defaultEventAction: 'stopEvent'
761         });
762         this.queryDelay = Math.max(this.queryDelay || 10,
763                 this.mode == 'local' ? 10 : 250);
764         this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
765         if(this.typeAhead){
766             this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
767         }
768         if(!this.enableKeyEvents){
769             this.mon(this.el, 'keyup', this.onKeyUp, this);
770         }
771     },
772
773     // private
774     onDestroy : function(){
775         if (this.dqTask){
776             this.dqTask.cancel();
777             this.dqTask = null;
778         }
779         this.bindStore(null);
780         Ext.destroy(
781             this.resizer,
782             this.view,
783             this.pageTb,
784             this.list
785         );
786         Ext.destroyMembers(this, 'hiddenField');
787         Ext.form.ComboBox.superclass.onDestroy.call(this);
788     },
789
790     // private
791     fireKey : function(e){
792         if (!this.isExpanded()) {
793             Ext.form.ComboBox.superclass.fireKey.call(this, e);
794         }
795     },
796
797     // private
798     onResize : function(w, h){
799         Ext.form.ComboBox.superclass.onResize.apply(this, arguments);
800         if(this.isVisible() && this.list){
801             this.doResize(w);
802         }else{
803             this.bufferSize = w;
804         }
805     },
806
807     doResize: function(w){
808         if(!Ext.isDefined(this.listWidth)){
809             var lw = Math.max(w, this.minListWidth);
810             this.list.setWidth(lw);
811             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
812         }
813     },
814
815     // private
816     onEnable : function(){
817         Ext.form.ComboBox.superclass.onEnable.apply(this, arguments);
818         if(this.hiddenField){
819             this.hiddenField.disabled = false;
820         }
821     },
822
823     // private
824     onDisable : function(){
825         Ext.form.ComboBox.superclass.onDisable.apply(this, arguments);
826         if(this.hiddenField){
827             this.hiddenField.disabled = true;
828         }
829     },
830
831     // private
832     onBeforeLoad : function(){
833         if(!this.hasFocus){
834             return;
835         }
836         this.innerList.update(this.loadingText ?
837                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
838         this.restrictHeight();
839         this.selectedIndex = -1;
840     },
841
842     // private
843     onLoad : function(){
844         if(!this.hasFocus){
845             return;
846         }
847         if(this.store.getCount() > 0 || this.listEmptyText){
848             this.expand();
849             this.restrictHeight();
850             if(this.lastQuery == this.allQuery){
851                 if(this.editable){
852                     this.el.dom.select();
853                 }
854                 if(!this.selectByValue(this.value, true)){
855                     this.select(0, true);
856                 }
857             }else{
858                 this.selectNext();
859                 if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
860                     this.taTask.delay(this.typeAheadDelay);
861                 }
862             }
863         }else{
864             this.onEmptyResults();
865         }
866         //this.el.focus();
867     },
868
869     // private
870     onTypeAhead : function(){
871         if(this.store.getCount() > 0){
872             var r = this.store.getAt(0);
873             var newValue = r.data[this.displayField];
874             var len = newValue.length;
875             var selStart = this.getRawValue().length;
876             if(selStart != len){
877                 this.setRawValue(newValue);
878                 this.selectText(selStart, newValue.length);
879             }
880         }
881     },
882
883     // private
884     onSelect : function(record, index){
885         if(this.fireEvent('beforeselect', this, record, index) !== false){
886             this.setValue(record.data[this.valueField || this.displayField]);
887             this.collapse();
888             this.fireEvent('select', this, record, index);
889         }
890     },
891
892     // inherit docs
893     getName: function(){
894         var hf = this.hiddenField;
895         return hf && hf.name ? hf.name : this.hiddenName || Ext.form.ComboBox.superclass.getName.call(this);
896     },
897
898     /**
899      * Returns the currently selected field value or empty string if no value is set.
900      * @return {String} value The selected value
901      */
902     getValue : function(){
903         if(this.valueField){
904             return Ext.isDefined(this.value) ? this.value : '';
905         }else{
906             return Ext.form.ComboBox.superclass.getValue.call(this);
907         }
908     },
909
910     /**
911      * Clears any text/value currently set in the field
912      */
913     clearValue : function(){
914         if(this.hiddenField){
915             this.hiddenField.value = '';
916         }
917         this.setRawValue('');
918         this.lastSelectionText = '';
919         this.applyEmptyText();
920         this.value = '';
921     },
922
923     /**
924      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
925      * will be displayed in the field.  If the value does not match the data value of an existing item,
926      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
927      * Otherwise the field will be blank (although the value will still be set).
928      * @param {String} value The value to match
929      * @return {Ext.form.Field} this
930      */
931     setValue : function(v){
932         var text = v;
933         if(this.valueField){
934             var r = this.findRecord(this.valueField, v);
935             if(r){
936                 text = r.data[this.displayField];
937             }else if(Ext.isDefined(this.valueNotFoundText)){
938                 text = this.valueNotFoundText;
939             }
940         }
941         this.lastSelectionText = text;
942         if(this.hiddenField){
943             this.hiddenField.value = v;
944         }
945         Ext.form.ComboBox.superclass.setValue.call(this, text);
946         this.value = v;
947         return this;
948     },
949
950     // private
951     findRecord : function(prop, value){
952         var record;
953         if(this.store.getCount() > 0){
954             this.store.each(function(r){
955                 if(r.data[prop] == value){
956                     record = r;
957                     return false;
958                 }
959             });
960         }
961         return record;
962     },
963
964     // private
965     onViewMove : function(e, t){
966         this.inKeyMode = false;
967     },
968
969     // private
970     onViewOver : function(e, t){
971         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
972             return;
973         }
974         var item = this.view.findItemFromChild(t);
975         if(item){
976             var index = this.view.indexOf(item);
977             this.select(index, false);
978         }
979     },
980
981     // private
982     onViewClick : function(doFocus){
983         var index = this.view.getSelectedIndexes()[0],
984             s = this.store,
985             r = s.getAt(index);
986         if(r){
987             this.onSelect(r, index);
988         }else if(s.getCount() === 0){
989             this.onEmptyResults();
990         }
991         if(doFocus !== false){
992             this.el.focus();
993         }
994     },
995
996     // private
997     restrictHeight : function(){
998         this.innerList.dom.style.height = '';
999         var inner = this.innerList.dom,
1000             pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight,
1001             h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight),
1002             ha = this.getPosition()[1]-Ext.getBody().getScroll().top,
1003             hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,
1004             space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
1005
1006         h = Math.min(h, space, this.maxHeight);
1007
1008         this.innerList.setHeight(h);
1009         this.list.beginUpdate();
1010         this.list.setHeight(h+pad);
1011         this.list.alignTo(this.wrap, this.listAlign);
1012         this.list.endUpdate();
1013     },
1014
1015     // private
1016     onEmptyResults : function(){
1017         this.collapse();
1018     },
1019
1020     /**
1021      * Returns true if the dropdown list is expanded, else false.
1022      */
1023     isExpanded : function(){
1024         return this.list && this.list.isVisible();
1025     },
1026
1027     /**
1028      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
1029      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
1030      * @param {String} value The data value of the item to select
1031      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
1032      * selected item if it is not currently in view (defaults to true)
1033      * @return {Boolean} True if the value matched an item in the list, else false
1034      */
1035     selectByValue : function(v, scrollIntoView){
1036         if(!Ext.isEmpty(v, true)){
1037             var r = this.findRecord(this.valueField || this.displayField, v);
1038             if(r){
1039                 this.select(this.store.indexOf(r), scrollIntoView);
1040                 return true;
1041             }
1042         }
1043         return false;
1044     },
1045
1046     /**
1047      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
1048      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
1049      * @param {Number} index The zero-based index of the list item to select
1050      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
1051      * selected item if it is not currently in view (defaults to true)
1052      */
1053     select : function(index, scrollIntoView){
1054         this.selectedIndex = index;
1055         this.view.select(index);
1056         if(scrollIntoView !== false){
1057             var el = this.view.getNode(index);
1058             if(el){
1059                 this.innerList.scrollChildIntoView(el, false);
1060             }
1061         }
1062     },
1063
1064     // private
1065     selectNext : function(){
1066         var ct = this.store.getCount();
1067         if(ct > 0){
1068             if(this.selectedIndex == -1){
1069                 this.select(0);
1070             }else if(this.selectedIndex < ct-1){
1071                 this.select(this.selectedIndex+1);
1072             }
1073         }
1074     },
1075
1076     // private
1077     selectPrev : function(){
1078         var ct = this.store.getCount();
1079         if(ct > 0){
1080             if(this.selectedIndex == -1){
1081                 this.select(0);
1082             }else if(this.selectedIndex !== 0){
1083                 this.select(this.selectedIndex-1);
1084             }
1085         }
1086     },
1087
1088     // private
1089     onKeyUp : function(e){
1090         var k = e.getKey();
1091         if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){
1092             this.lastKey = k;
1093             this.dqTask.delay(this.queryDelay);
1094         }
1095         Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
1096     },
1097
1098     // private
1099     validateBlur : function(){
1100         return !this.list || !this.list.isVisible();
1101     },
1102
1103     // private
1104     initQuery : function(){
1105         this.doQuery(this.getRawValue());
1106     },
1107
1108     // private
1109     beforeBlur : function(){
1110         var val = this.getRawValue(),
1111             rec = this.findRecord(this.displayField, val);
1112         if(!rec && this.forceSelection){
1113             if(val.length > 0 && val != this.emptyText){
1114                 this.el.dom.value = Ext.isEmpty(this.lastSelectionText) ? '' : this.lastSelectionText;
1115                 this.applyEmptyText();
1116             }else{
1117                 this.clearValue();
1118             }
1119         }else{
1120             if(rec){
1121                 val = rec.get(this.valueField || this.displayField);
1122             }
1123             this.setValue(val);
1124         }
1125     },
1126
1127     /**
1128      * Execute a query to filter the dropdown list.  Fires the {@link #beforequery} event prior to performing the
1129      * query allowing the query action to be canceled if needed.
1130      * @param {String} query The SQL query to execute
1131      * @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
1132      * characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option.  It
1133      * also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
1134      */
1135     doQuery : function(q, forceAll){
1136         q = Ext.isEmpty(q) ? '' : q;
1137         var qe = {
1138             query: q,
1139             forceAll: forceAll,
1140             combo: this,
1141             cancel:false
1142         };
1143         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
1144             return false;
1145         }
1146         q = qe.query;
1147         forceAll = qe.forceAll;
1148         if(forceAll === true || (q.length >= this.minChars)){
1149             if(this.lastQuery !== q){
1150                 this.lastQuery = q;
1151                 if(this.mode == 'local'){
1152                     this.selectedIndex = -1;
1153                     if(forceAll){
1154                         this.store.clearFilter();
1155                     }else{
1156                         this.store.filter(this.displayField, q);
1157                     }
1158                     this.onLoad();
1159                 }else{
1160                     this.store.baseParams[this.queryParam] = q;
1161                     this.store.load({
1162                         params: this.getParams(q)
1163                     });
1164                     this.expand();
1165                 }
1166             }else{
1167                 this.selectedIndex = -1;
1168                 this.onLoad();
1169             }
1170         }
1171     },
1172
1173     // private
1174     getParams : function(q){
1175         var p = {};
1176         //p[this.queryParam] = q;
1177         if(this.pageSize){
1178             p.start = 0;
1179             p.limit = this.pageSize;
1180         }
1181         return p;
1182     },
1183
1184     /**
1185      * Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
1186      */
1187     collapse : function(){
1188         if(!this.isExpanded()){
1189             return;
1190         }
1191         this.list.hide();
1192         Ext.getDoc().un('mousewheel', this.collapseIf, this);
1193         Ext.getDoc().un('mousedown', this.collapseIf, this);
1194         this.fireEvent('collapse', this);
1195     },
1196
1197     // private
1198     collapseIf : function(e){
1199         if(!e.within(this.wrap) && !e.within(this.list)){
1200             this.collapse();
1201         }
1202     },
1203
1204     /**
1205      * Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
1206      */
1207     expand : function(){
1208         if(this.isExpanded() || !this.hasFocus){
1209             return;
1210         }
1211         if(this.bufferSize){
1212             this.doResize(this.bufferSize);
1213             delete this.bufferSize;
1214         }
1215         this.list.alignTo(this.wrap, this.listAlign);
1216         this.list.show();
1217         if(Ext.isGecko2){
1218             this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
1219         }
1220         this.mon(Ext.getDoc(), {
1221             scope: this,
1222             mousewheel: this.collapseIf,
1223             mousedown: this.collapseIf
1224         });
1225         this.fireEvent('expand', this);
1226     },
1227
1228     /**
1229      * @method onTriggerClick
1230      * @hide
1231      */
1232     // private
1233     // Implements the default empty TriggerField.onTriggerClick function
1234     onTriggerClick : function(){
1235         if(this.readOnly || this.disabled){
1236             return;
1237         }
1238         if(this.isExpanded()){
1239             this.collapse();
1240             this.el.focus();
1241         }else {
1242             this.onFocus({});
1243             if(this.triggerAction == 'all') {
1244                 this.doQuery(this.allQuery, true);
1245             } else {
1246                 this.doQuery(this.getRawValue());
1247             }
1248             this.el.focus();
1249         }
1250     }
1251
1252     /**
1253      * @hide
1254      * @method autoSize
1255      */
1256     /**
1257      * @cfg {Boolean} grow @hide
1258      */
1259     /**
1260      * @cfg {Number} growMin @hide
1261      */
1262     /**
1263      * @cfg {Number} growMax @hide
1264      */
1265
1266 });
1267 Ext.reg('combo', Ext.form.ComboBox);