当我们在Combox 中定义了PageSize属性,那么Combox 自动获得了分页的能力。这本身很好,但是带来一个问题。
这个问题的发生是因为,Combox组件有一个特点。当你想用程序控制,让下拉列表中的某一项成为当前选中项时,这个项必须是在列表中存在的(有点像废话)。 意思就是说,如果你列表里有A,B,C,D 4个选项, Combox分了页,AB在第一页,CD在第二页,而默认情况下拉列表中只有第一页的内容,就是只有AB, 那么你想让Combox当前的值是D , 就实现不了了。
这种情况经常出现在,当你想让用户在某个Grid列表里点击一个记录,选择一个“修改”,接下来弹出的修改窗口中有个Combox,Combox自动选中了这条记录原先选中的值。 这种情况如果原先的值是在Combox的第二页, 你就傻眼了。
下面的代码解决了上述问题。
//Define a record structure
var consignerRecord = Ext.data.Record.create([
{name:"consignerId"},
{name:"consignerName"}
]);
//this is the store
comboxConsignerStore = new Ext.data.JsonStore({
url:'/pcms/dictionary/consigner.do?method=findConsigners',
root:'Datas',
totalProperty: 'TotalRecords',
fields:[
{name:'consignerId', mapping:'consignerId'},
{name:'consignerName', mapping:'consignerName'}
]
});
//ah ,the combox with pagebar
var comboxConsigner = new Ext.form.ComboBox({
name:'consignerId',
hiddenName:'consignerId',
displayField:'consignerName',
valueField:'consignerId',
emptyText:'请选择',
fieldLabel:'供货方',
width:200,
editable:false,
allowBlank:false,
mode:'remote',
loadingText:'loading...',
pageSize:10,
selectOnFocus: true,
triggerAction:'all',
store: comboxConsignerStore
});
//上例中的修改窗体,就是这个了
var UpdateWindow = new Ext.Window({
title:'新增合同',
layout:'fit',
items:[formPanel],
model:true,
width:450,
height:450,
listeners:{
//关键点来了,beforeshow,在窗体显示之前,我们对combox进行些处理
beforeshow: function(){
if(grid.getSelectionModel().getSelected() != null){ //首先保证用户得选中了记录
//处理ConsigneeCombox
var cr = new consigneeRecord({// 创建一条新的consignee记录,为以后插入做准备
consigneeId: grid.getSelectionModel().getSelected().get("consigneeId"),//记录内的值是从用户选中的Grid记录中取的
consigneeName: grid.getSelectionModel().getSelected().get("consigneeName")//同上
});
//又是重点,filterBy 函数, 可以通过这个,控制store的记录,返回true,就允许一条记录插入到stroe里,返货false就抛弃掉本条记录。
//store里每条记录都会过一遍这个方法,所以我们就在这里判断,把用户在Grid选中的那条记录里的combox记录给抛弃掉,
//为以后插入做准备
comboxConsigneeStore.filterBy(function(aRecord,aId){
if(aRecord.get("consigneeId") == grid.getSelectionModel().getSelected().get("consigneeId")){
return false;
}
return true;
});
//插入用户在Grid上选中的记录对应的那条combox记录,然后再控制选中,就满足了combox的特点。
comboxConsigneeStore.insert(0,cr);
comboxConsignee.setValue(comboxConsignee.getValue());
}
}
}
});