ExtJs 3.0 动态生成 CheckBox

时间:2023-03-10 04:14:47
ExtJs 3.0 动态生成 CheckBox

在开发过程中,往往需要利用数据动态生成Checkbox。如权限节点。考试答案,调查选项等等。在Extjs中,有两种方法来获取后台数据,一是Ext.Ajax()方法,第二种是利用 Store,store其实也是利用ajax方式来获取,下面以利用Store的方式来实现动态生成。

1、定义Store

       //定义store
var customFieds = new Ext.data.Store({
url: ‘Controls/GetFields',
remoteSort: true,
reader: new Ext.data.JsonReader({
root: 'data',
totalProperty: 'total',
id: 'Id'
}, [
{ name: 'Id', type: 'string' },
{ name: 'Name', type: 'string' },
{name: 'FieldType', type: 'string'},
{name: 'IsChecked', type: 'string'}
])
});

2、生成

/**
* 生成Checkbox
*
*/
function generateCheckbox() { //以store动态生成Checkbox
var items = [];
for (var i = 0; i < customFieds.getCount(); i++) {
var d = customFieds.getAt(i);
var chk = { id: d.get('Id'), boxLabel: d.get('Name'), name: 'LableFields',inputValue:d.get('Id'),checked :d.get('IsChecked')=='true'?true:false };
items.push(chk);
}
var CheckBoxGroupTypes = new Ext.form.CheckboxGroup({
xtype: 'checkboxgroup',
fieldLabel: 'Field<span style="color: red;" >*</span>',
id: 'Field',
allowBlank: false,
name: 'LableFields',
columns: 3,
anchor: "95%",
msgTarget: "side"
});
CheckBoxGroupTypes.items = items;
var singleColumn1 = [
CheckBoxGroupTypes
]; var form = new Ext.FormPanel({
border: false,
waitMsgTarget: true,
labelWidth: 100,
frame: true,
fileUpload: true,
bodyStyle: 'padding:5px 5px 0',
labelAlign: 'right',
items: singleColumn1,
buttonAlign: 'center',
buttons: [new Ext.ux.SubmitBtn({
text: 'Submit.',
handler: function() {
if (form.getForm().isValid()) {
form.getForm().submit({
url: 'Control/SaveOrUpdate',
params: {
"Id": id
},
waitMsg: 'save...',
timeout: 2000 * 1000,
success: function (form, action) {
if (action.result.success) {
win.destroy();
FieldRuleStore.load({ params: {
start: 0,
limit: ALL_PAGESIZE_SETTING
}
});
}
},
failure: function (form, action) {
Ext.Msg.show(action.result.msg); }
});
}
}
}), new Ext.ux.CancelBtn({
text: 'Exit',
handler: function() {
win.destroy();
}
})]
});
var win = new Ext.Window({
id: ‘id',
title: title,
iconCls: 'application_form',
width: 500,
resizable: false,
constrain: true,
autoHeight: true,
modal: true,
closeAction: 'close',
plain: true,
items: [form]
});
win.show(); }

3、回调生成,回调的原因是因为extjs store获取数据是使用ajax方式获取。回调就是要在获取数据成功后才动态生成。

customFieds.load({
params: {
Id:id
},
callback: function(r, option, sucess)
{ generateCheckbox(); }
});

4、效果图

ExtJs 3.0 动态生成 CheckBox