ExtJS Grid嵌入动态ComboBox实现
作者:技术拾光时间:2026-06-12 08:32:02浏览:299
在ExtJS的EditorGridPanel中嵌入动态ComboBox时,需先定义JsonStore拉取下拉选项,且ComboBox必须设置id属性。通过自定义renderer函数,依据ComboBox的store将id值转换为对应的显示文本,从而解决单元格编辑后显示为id而非文本的问题。
首先,处理 ComboBox 的数据来源。需要定义一个 JsonStore,用于从后端接口获取下拉选项。字段包含 id 和 display,分别对应值字段和显示字段。
comboDS = new Ext.data.JsonStore({
url : 'test.do',
fields : [{
name : 'id'
}, {
name : 'display'
}]
});
ComboBox 定义
定义 ComboBox 时,有一个关键点:id 属性是必需的,后续需要通过它获取组件实例。其他常见配置如 typeAhead、readOnly、forceSelection 等按需设置。emptyText 给出提示,displayField 和 valueField 对应 store 中的字段。
var comboBox = new Ext.form.ComboBox({
id : "cb", // 必须有
typeAhead : true,
readOnly : true,
allowBlank : false,
autoScroll : true,
selectOnFocus : true,
emptyText : '请选择...',
store : comboDS,
forceSelection : true,
triggerAction : 'all',
displayField : 'display',
valueField : 'id'
});
Grid 的定义
接着搭建 EditorGridPanel。数据源使用 HttpProxy 请求 test2.do,分页参数通过 baseparams 传递。列模型中,测试列指定 editor 为刚才定义的 ComboBox,同时设置了一个自定义的 renderer 函数,用于处理单元格的显示。
ds = new Ext.data.Store({
baseparams : {
start : 0,
limit : RowCount
},
proxy : new Ext.data.HttpProxy({
url :'test2.do'
}),
reader : new Ext.data.JsonReader({
root : 'data',
totalProperty : 'totalCount'
}, [{
name : "bh"
}, {
name : "test"
}]);
});
var cm = new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
{
header : "编号",
dataIndex : "bh"
},
{
header : "测试",
dataIndex : "test",
renderer : renderer,
editor : comboBox
}
]);
grid = new Ext.grid.EditorGridPanel({
title : '测试',
ds : ds,
cm : cm,
clicksToEdit : 1,
viewConfig : {
forceFit : true
},
bbar : new Ext.PagingToolbar({
pageSize : RowCount,
store : ds,
displayInfo : true,
displayMsg : '显示第 {0} 条到 {1} 条记录,一共 {2} 条',
emptyMsg : "没有记录"
})
});
ColumnModel 的 renderer 函数
这个 renderer 函数的作用很关键——解决 ComboBox 修改后单元格显示为 id 值而不是显示文本的问题。通过 ComboBox 的 store 查找对应记录,取出 display 字段来展示。如果找不到记录,则兜底显示原始值。
function renderer(value, p, r) {
var index = comboDS.find(Ext.getCmp('cb').valueField, value);
var record = comboDS.getAt(index);
var displayText = "";
if (record == null) {
displayText = value;
} else {
displayText = record.data.display; // 获取record中的数据集中的display字段的值
}
}
