source: trunk/web/addons/job_monarch/lib/extjs-30/src/widgets/form/Combo.js @ 625

Last change on this file since 625 was 625, checked in by ramonb, 15 years ago

lib/extjs-30:

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