3 * Copyright(c) 2008-2011 Alan Knowles
10 * @class Roo.form.ComboCheck
11 * @extends Roo.form.ComboBox
12 * A combobox for multiple select items.
14 * Create a new ComboCheck
15 * @param {Object} config Configuration options
17 Roo.form.ComboCheck = function(config){
18 Roo.form.ComboCheck.superclass.constructor.call(this, config);
22 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
24 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
27 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
28 * rendering into an Roo.Editor, defaults to false)
31 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
32 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
35 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
38 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
39 * the dropdown list (defaults to undefined, with no header element)
43 * @cfg {String/Roo.Template} tpl The template to use to render the output
47 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
49 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
53 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
54 * mode = 'remote' or 'text' if mode = 'local')
56 displayField: undefined,
58 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
59 * mode = 'remote' or 'value' if mode = 'local').
60 * Note: use of a valueField requires the user make a selection
61 * in order for a value to be mapped.
63 valueField: undefined,
65 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
66 * field's data value (defaults to the underlying DOM element's name)
68 hiddenName: undefined,
70 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
74 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
76 selectedClass: 'x-combo-selected',
78 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
79 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
80 * which displays a downward arrow icon).
82 triggerClass : 'x-form-arrow-trigger',
84 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
88 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
89 * anchor positions (defaults to 'tl-bl')
93 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
97 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
98 * query specified by the allQuery config option (defaults to 'query')
100 triggerAction: 'query',
102 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
103 * (defaults to 4, does not apply if editable = false)
107 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
108 * delay (typeAheadDelay) if it matches a known value (defaults to false)
112 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
113 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
117 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
118 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
122 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
123 * when editable = true (defaults to false)
127 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
131 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
132 * when mode = 'remote' (defaults to 'Loading...')
134 loadingText: 'Loading...',
136 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
140 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
144 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
145 * traditional select (defaults to true)
149 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
153 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
157 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
158 * listWidth has a higher value)
162 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
163 * allow the user to set arbitrary text into the field (defaults to false)
165 forceSelection:false,
167 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
168 * if typeAhead = true (defaults to 250)
170 typeAheadDelay : 250,
172 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
173 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
175 valueNotFoundText : undefined,
177 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
182 * @cfg {Boolean} disableClear Disable showing of clear button.
184 disableClear : false,
186 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
196 onRender : function(ct, position){
197 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
199 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
201 this.hiddenField.value =
202 this.hiddenValue !== undefined ? this.hiddenValue :
203 this.value !== undefined ? this.value : '';
205 // prevent input submission
206 this.el.dom.removeAttribute('name');
209 this.el.dom.setAttribute('autocomplete', 'off');
212 var cls = 'x-combo-list';
214 this.list = new Roo.Layer({
215 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
218 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
219 this.list.setWidth(lw);
220 this.list.swallowEvent('mousewheel');
221 this.assetHeight = 0;
224 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
225 this.assetHeight += this.header.getHeight();
228 this.innerList = this.list.createChild({cls:cls+'-inner'});
229 this.innerList.on('mouseover', this.onViewOver, this);
230 this.innerList.on('mousemove', this.onViewMove, this);
231 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
233 if(this.allowBlank && !this.pageSize && !this.disableClear){
234 this.footer = this.list.createChild({cls:cls+'-ft'});
235 this.pageTb = new Roo.Toolbar(this.footer);
239 this.footer = this.list.createChild({cls:cls+'-ft'});
240 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
241 {pageSize: this.pageSize});
245 if (this.pageTb && this.allowBlank && !this.disableClear) {
247 this.pageTb.add(new Roo.Toolbar.Fill(), {
248 cls: 'x-btn-icon x-btn-clear',
254 _this.onSelect(false, -1);
259 this.assetHeight += this.footer.getHeight();
264 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
267 this.view = new Roo.View(this.innerList, this.tpl, {
268 singleSelect:true, store: this.store, selectedClass: this.selectedClass
271 this.view.on('click', this.onViewClick, this);
273 this.store.on('beforeload', this.onBeforeLoad, this);
274 this.store.on('load', this.onLoad, this);
275 this.store.on('loadexception', this.collapse, this);
278 this.resizer = new Roo.Resizable(this.list, {
279 pinned:true, handles:'se'
281 this.resizer.on('resize', function(r, w, h){
282 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
284 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
285 this.restrictHeight();
287 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
290 this.editable = true;
291 this.setEditable(false);
295 if (typeof(this.events.add.listeners) != 'undefined') {
297 this.addicon = this.wrap.createChild(
298 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
300 this.addicon.on('click', function(e) {
301 this.fireEvent('add', this);
304 if (typeof(this.events.edit.listeners) != 'undefined') {
306 this.editicon = this.wrap.createChild(
307 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
309 this.editicon.setStyle('margin-left', '40px');
311 this.editicon.on('click', function(e) {
313 // we fire even if inothing is selected..
314 this.fireEvent('edit', this, this.lastData );
324 initEvents : function(){
325 Roo.form.ComboBox.superclass.initEvents.call(this);
327 this.keyNav = new Roo.KeyNav(this.el, {
329 this.inKeyMode = true;
333 "down" : function(e){
334 if(!this.isExpanded()){
335 this.onTriggerClick();
337 this.inKeyMode = true;
342 "enter" : function(e){
352 this.onViewClick(false);
358 doRelay : function(foo, bar, hname){
359 if(hname == 'down' || this.scope.isExpanded()){
360 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
367 this.queryDelay = Math.max(this.queryDelay || 10,
368 this.mode == 'local' ? 10 : 250);
369 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
371 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
373 if(this.editable !== false){
374 this.el.on("keyup", this.onKeyUp, this);
376 if(this.forceSelection){
377 this.on('blur', this.doForce, this);
381 onDestroy : function(){
383 this.view.setStore(null);
384 this.view.el.removeAllListeners();
385 this.view.el.remove();
386 this.view.purgeListeners();
392 this.store.un('beforeload', this.onBeforeLoad, this);
393 this.store.un('load', this.onLoad, this);
394 this.store.un('loadexception', this.collapse, this);
396 Roo.form.ComboBox.superclass.onDestroy.call(this);
400 fireKey : function(e){
401 if(e.isNavKeyPress() && !this.list.isVisible()){
402 this.fireEvent("specialkey", this, e);
407 onResize: function(w, h){
408 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
410 if(typeof w != 'number'){
411 // we do not handle it!?!?
414 var tw = this.trigger.getWidth();
415 tw += this.addicon ? this.addicon.getWidth() : 0;
416 tw += this.editicon ? this.editicon.getWidth() : 0;
418 this.el.setWidth( this.adjustWidth('input', x));
420 this.trigger.setStyle('left', x+'px');
422 if(this.list && this.listWidth === undefined){
423 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
424 this.list.setWidth(lw);
425 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
433 * Allow or prevent the user from directly editing the field text. If false is passed,
434 * the user will only be able to select from the items defined in the dropdown list. This method
435 * is the runtime equivalent of setting the 'editable' config option at config time.
436 * @param {Boolean} value True to allow the user to directly edit the field text
438 setEditable : function(value){
439 if(value == this.editable){
442 this.editable = value;
444 this.el.dom.setAttribute('readOnly', true);
445 this.el.on('mousedown', this.onTriggerClick, this);
446 this.el.addClass('x-combo-noedit');
448 this.el.dom.setAttribute('readOnly', false);
449 this.el.un('mousedown', this.onTriggerClick, this);
450 this.el.removeClass('x-combo-noedit');
455 onBeforeLoad : function(){
459 this.innerList.update(this.loadingText ?
460 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
461 this.restrictHeight();
462 this.selectedIndex = -1;
470 if(this.store.getCount() > 0){
472 this.restrictHeight();
473 if(this.lastQuery == this.allQuery){
475 this.el.dom.select();
477 if(!this.selectByValue(this.value, true)){
478 this.select(0, true);
482 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
483 this.taTask.delay(this.typeAheadDelay);
487 this.onEmptyResults();
493 onTypeAhead : function(){
494 if(this.store.getCount() > 0){
495 var r = this.store.getAt(0);
496 var newValue = r.data[this.displayField];
497 var len = newValue.length;
498 var selStart = this.getRawValue().length;
500 this.setRawValue(newValue);
501 this.selectText(selStart, newValue.length);
507 onSelect : function(record, index){
508 if(this.fireEvent('beforeselect', this, record, index) !== false){
509 this.setFromData(index > -1 ? record.data : false);
511 this.fireEvent('select', this, record, index);
516 * Returns the currently selected field value or empty string if no value is set.
517 * @return {String} value The selected value
519 getValue : function(){
521 return typeof this.value != 'undefined' ? this.value : '';
523 return Roo.form.ComboBox.superclass.getValue.call(this);
528 * Clears any text/value currently set in the field
530 clearValue : function(){
531 if(this.hiddenField){
532 this.hiddenField.value = '';
535 this.setRawValue('');
536 this.lastSelectionText = '';
537 this.applyEmptyText();
541 * Sets the specified value into the field. If the value finds a match, the corresponding record text
542 * will be displayed in the field. If the value does not match the data value of an existing item,
543 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
544 * Otherwise the field will be blank (although the value will still be set).
545 * @param {String} value The value to match
547 setValue : function(v){
550 var r = this.findRecord(this.valueField, v);
552 text = r.data[this.displayField];
553 }else if(this.valueNotFoundText !== undefined){
554 text = this.valueNotFoundText;
557 this.lastSelectionText = text;
558 if(this.hiddenField){
559 this.hiddenField.value = v;
561 Roo.form.ComboBox.superclass.setValue.call(this, text);
565 * @property {Object} the last set data for the element
570 * Sets the value of the field based on a object which is related to the record format for the store.
571 * @param {Object} value the value to set as. or false on reset?
573 setFromData : function(o){
574 var dv = ''; // display value
575 var vv = ''; // value value..
577 if (this.displayField) {
578 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
580 // this is an error condition!!!
581 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
585 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
587 if(this.hiddenField){
588 this.hiddenField.value = vv;
590 this.lastSelectionText = dv;
591 Roo.form.ComboBox.superclass.setValue.call(this, dv);
595 // no hidden field.. - we store the value in 'value', but still display
597 this.lastSelectionText = dv;
598 Roo.form.ComboBox.superclass.setValue.call(this, dv);
605 // overridden so that last data is reset..
606 this.setValue(this.originalValue);
608 this.lastData = false;
611 findRecord : function(prop, value){
613 if(this.store.getCount() > 0){
614 this.store.each(function(r){
615 if(r.data[prop] == value){
625 onViewMove : function(e, t){
626 this.inKeyMode = false;
630 onViewOver : function(e, t){
631 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
634 var item = this.view.findItemFromChild(t);
636 var index = this.view.indexOf(item);
637 this.select(index, false);
642 onViewClick : function(doFocus){
643 var index = this.view.getSelectedIndexes()[0];
644 var r = this.store.getAt(index);
646 this.onSelect(r, index);
648 if(doFocus !== false && !this.blockFocus){
654 restrictHeight : function(){
655 this.innerList.dom.style.height = '';
656 var inner = this.innerList.dom;
657 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
658 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
659 this.list.beginUpdate();
660 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
661 this.list.alignTo(this.el, this.listAlign);
662 this.list.endUpdate();
666 onEmptyResults : function(){
671 * Returns true if the dropdown list is expanded, else false.
673 isExpanded : function(){
674 return this.list.isVisible();
678 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
679 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
680 * @param {String} value The data value of the item to select
681 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
682 * selected item if it is not currently in view (defaults to true)
683 * @return {Boolean} True if the value matched an item in the list, else false
685 selectByValue : function(v, scrollIntoView){
686 if(v !== undefined && v !== null){
687 var r = this.findRecord(this.valueField || this.displayField, v);
689 this.select(this.store.indexOf(r), scrollIntoView);
697 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
698 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
699 * @param {Number} index The zero-based index of the list item to select
700 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
701 * selected item if it is not currently in view (defaults to true)
703 select : function(index, scrollIntoView){
704 this.selectedIndex = index;
705 this.view.select(index);
706 if(scrollIntoView !== false){
707 var el = this.view.getNode(index);
709 this.innerList.scrollChildIntoView(el, false);
715 selectNext : function(){
716 var ct = this.store.getCount();
718 if(this.selectedIndex == -1){
720 }else if(this.selectedIndex < ct-1){
721 this.select(this.selectedIndex+1);
727 selectPrev : function(){
728 var ct = this.store.getCount();
730 if(this.selectedIndex == -1){
732 }else if(this.selectedIndex != 0){
733 this.select(this.selectedIndex-1);
739 onKeyUp : function(e){
740 if(this.editable !== false && !e.isSpecialKey()){
741 this.lastKey = e.getKey();
742 this.dqTask.delay(this.queryDelay);
747 validateBlur : function(){
748 return !this.list || !this.list.isVisible();
752 initQuery : function(){
753 this.doQuery(this.getRawValue());
757 doForce : function(){
758 if(this.el.dom.value.length > 0){
760 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
761 this.applyEmptyText();
766 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
767 * query allowing the query action to be canceled if needed.
768 * @param {String} query The SQL query to execute
769 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
770 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
771 * saved in the current store (defaults to false)
773 doQuery : function(q, forceAll){
774 if(q === undefined || q === null){
783 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
787 forceAll = qe.forceAll;
788 if(forceAll === true || (q.length >= this.minChars)){
789 if(this.lastQuery != q || this.alwaysQuery){
791 if(this.mode == 'local'){
792 this.selectedIndex = -1;
794 this.store.clearFilter();
796 this.store.filter(this.displayField, q);
800 this.store.baseParams[this.queryParam] = q;
802 params: this.getParams(q)
807 this.selectedIndex = -1;
814 getParams : function(q){
816 //p[this.queryParam] = q;
819 p.limit = this.pageSize;
825 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
827 collapse : function(){
828 if(!this.isExpanded()){
832 Roo.get(document).un('mousedown', this.collapseIf, this);
833 Roo.get(document).un('mousewheel', this.collapseIf, this);
834 if (!this.editable) {
835 Roo.get(document).un('keydown', this.listKeyPress, this);
837 this.fireEvent('collapse', this);
841 collapseIf : function(e){
842 if(!e.within(this.wrap) && !e.within(this.list)){
848 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
851 if(this.isExpanded() || !this.hasFocus){
854 this.list.alignTo(this.el, this.listAlign);
856 Roo.get(document).on('mousedown', this.collapseIf, this);
857 Roo.get(document).on('mousewheel', this.collapseIf, this);
858 if (!this.editable) {
859 Roo.get(document).on('keydown', this.listKeyPress, this);
862 this.fireEvent('expand', this);
866 // Implements the default empty TriggerField.onTriggerClick function
867 onTriggerClick : function(){
871 if(this.isExpanded()){
873 if (!this.blockFocus) {
878 this.hasFocus = true;
879 if(this.triggerAction == 'all') {
880 this.doQuery(this.allQuery, true);
882 this.doQuery(this.getRawValue());
884 if (!this.blockFocus) {
889 listKeyPress : function(e)
891 //Roo.log('listkeypress');
892 // scroll to first matching element based on key pres..
893 if (e.isSpecialKey()) {
896 var k = String.fromCharCode(e.getKey()).toUpperCase();
899 var csel = this.view.getSelectedNodes();
900 var cselitem = false;
902 var ix = this.view.indexOf(csel[0]);
903 cselitem = this.store.getAt(ix);
904 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
910 this.store.each(function(v) {
912 // start at existing selection.
913 if (cselitem.id == v.id) {
919 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
920 match = this.store.indexOf(v);
925 if (match === false) {
926 return true; // no more action?
929 this.view.select(match);
930 var sn = Roo.get(this.view.getSelectedNodes()[0])
931 sn.scrollIntoView(sn.dom.parentNode, false);
935 * @cfg {Boolean} grow
939 * @cfg {Number} growMin
943 * @cfg {Number} growMax