做项目时,很多的下拉列表值都是从后台获取的,而查询时,用户往往需要提供一个“全部”查询项,或空查询项。
本文就介绍项目中的一个实例。从后台数据库查询专业,形成专业combo,前台显示时会比查询出来的数据多一个“全部”选项。
先看最后实现的效果
分析实现的原理,如果想动态添加一个查询项,则必须是combo的store加载完毕后再操作store,
此时可以给store加一个监听,当load的时候,调用store的insert方法。具体例子如下(主要方法是initStore()方法)
/**
* 专业大类combo
* @author yangchuanhuan
*/
App.zydlListCombo = Ext.extend(Ext.form.ComboBox,{
fieldLabel : '专业大类',
triggerAction: 'all',
loadingText: '正在加载...',
mode : 'remote',
valueField : 'id',
displayField : 'text',
typeAhead:false,
editable : false,
resizable :true,
hasNullValue:true,//是否添加'全部'下拉列表
initComponent : function(){
this.store = new Ext.data.Store({//默认store
autoLoad : false,
proxy : new Ext.data.HttpProxy({
url:'processManager/zz-aid-sub-list!queryZyDlByZyMl.action'
}),
reader :new Ext.data.JsonReader({
totalProperty: 'totalProperty',
root: 'results'
},[
{name:'id'},
{name:'text'}
])
});
this.initStore();
App.zydlListCombo.superclass.initComponent.call(this);
},
initStore:function(){
var thisCombo = this;
//判断是否需要添加空值
if(thisCombo.hasNullValue){
thisCombo.store.on('load',function(store,record){
var nullValue = new store.recordType({id:'',text:'全部'});
store.insert(0,nullValue);
}
});
}
//store加载完后,重新设置value,然后自动匹配RawValue
thisCombo.store.on('load',function(store,records,options){
this.setValue(this.getValue());
this.clearInvalid();
},this);
}
});
Ext.reg('zydlListCombo', App.zydlListCombo);
注意,如果该combo是通用combo,store必须要放到initComponent中。因为如果放在盒initStore()并列的话,则该store相当于一个静态变量。
所有对象公用同一个store,如果页面中有两个地方同时使用该combo,下拉框中就会出现两个“全部”选项