FormPanel,EditorGridPanel的赋值和传参、数据的保存删除
程序员文章站
2022-05-13 14:12:20
...
FormPanel,EditorGridPanel的赋值和传参、数据的保存删除
首先,需要注意几个问题:
1.我们最常用的Store都是用于Grid取值,用columnModel中的dataIndex关联Store的fields。
2.Formpanel数据源和Grid相同,一般使用以下两种方式赋值:
(1).getForm().findField("name").setValue("") —— 此处用name赋值
var addForm = new Ext.FormPanel({ frame: true, labelWidth: 80, //labelAlign: "right", //buttonAlign:"center", items:[ xmmcCombox, { name:"xmdw", xtype:"textfield", fieldLabel:"项目单位", readOnly:true, width:200 },{ name:"depart", xtype:"textfield", fieldLabel:"主管部门", readOnly:true, width:200 } ] }); itemStore.on('load', function (store, record, options) { var comp = record[0].get("company"); var dept = record[0].data.department; addForm.getForm().findField("xmdw").setValue(comp); addForm.getForm().findField("depart").setValue(dept); });
(2).Ext.getCmp("id").setValue("") ——此处用id赋值
var addForm = new Ext.FormPanel({ frame: true, labelWidth: 80, //labelAlign: "right", //buttonAlign:"center", items:[ xmmcCombox, { id:"xmdw", xtype:"textfield", fieldLabel:"项目单位", readOnly:true, width:200 },{ id:"depart", xtype:"textfield", fieldLabel:"主管部门", readOnly:true, width:200 } ] }); itemStore.on('load', function (store, record, options) { var comp = record[0].get("company"); var dept = record[0].data.department; Ext.getCmp("xmdw").setValue(comp); Ext.getCmp("depart").setValue(dept); });
3.Ext.getCmp("id")适用于FormPanel中的元素,不适用于Grid
var cm = new Ext.grid.ColumnModel({ columns:[ { id:"id", header:"编号", dataIndex:"id", width:200, hidden:true },{ header:"项目编号", dataIndex:"xmid", width:200, hidden:true, editor:new Ext.form.TextField({ id:"xmid" }) } ] }); //注: 1.此处用了editor,则Grid需要用EditorGridPanel才能生效 2.此处若想取编号对应的值,用Ext.getCmp("id"),会报错。 像项目编号这样,加上一个editor,增加一个TextField,则用Ext.getCmp("xmid")可以获得项目编号元素,并可继续通过getValue()取值,setValue()赋值。
实例分析:
1.创建表格面板:
/*-----1.创建数据源-----*/ var epStore = new Ext.data.JsonStore({ autoLoad: true, url:"getEProject.eva?doType=getEProject", root:"data", fields: ["xmid","project","company","other"] }); /*-----1.定义列-----*/ var cm = new Ext.grid.ColumnModel({ columns:[ { header:"项目名称", dataIndex:"project", width:200, sortable:true },{ header:"项目单位", dataIndex:"company", width:200, sortable:true },{ header:"项目基本情况", dataIndex:"other", width:100, sortable:true, renderer:function(value, cell, record, row, column, store){ return " <a href='javascript:showBasicMsg()'>点击查看</a>"; } },{ header:"项目支出明细", dataIndex:"other", width:100, sortable:true, renderer:function(value, cell, record, row, column, store){ return " <a href='javascript:showCostWin("+record.get("xmid")+")'>点击查看</a>"; } },{ header:"项目绩效评分", dataIndex:"", width:100, sortable:true, renderer:function(){ return " <button class='btn1' onclick='showScoreWin("+record.get("xmid")+")'>查看</button>"; } } ] }); //4.创建表格面板 var grid = new Ext.grid.GridPanel({ store:epStore, cm:cm, loadMask:{msg:'正在加载数据,请稍侯……'}, height:80, tbar:[ { text:"增加项目", iconCls:"add", handler:function(){ addWin.show(); } },{ text:"修改", iconCls:"edit" },{ text:"删除", iconCls:"remove" } ] });后台返回数据:
注意事项:
1.返回的json数据只有3个字段,而Store定义的fields有4个,多了一个other,
说明fields字段可以多于后台返回的json数据的字段数!
2.若要对单元格执行renderer方法,则其dataIndex应该和Store的fields某一个字段对应!
(但是如果不想该单元格出现数据,则此时可用多出来的无数据的other!)
当然,dataIndex为空也是可以的:
通过调用方法传递参数:
//显示收支明细窗口 function showCostWin(xmid){ Ext.getCmp("costXmid").setValue(xmid); costWin.show(); costStore.baseParams.xmid = xmid; costStore.load(); }注:此处先给store的参数赋值(参数不用先定义!),然后在load().
2.创建收支明细窗口:
/*1.创建Record*/ var costRecord = new Ext.data.Record.create([ {name:"id",type:"int"}, {name:"xmid",type:"int"}, {name:"subject",type:"string"}, {name:"planCost",type:"string"}, {name:"actualCost",type:"string"} ]); /*2.创建Store*/ var costStore = new Ext.data.Store({ url:"getProjectCost.eva?doType=getProjectCost", reader: new Ext.data.JsonReader({ root:"data" },costRecord) }); /*3.创建列*/ var cm = new Ext.grid.ColumnModel({ columns:[ { header:"编号", dataIndex:"id", width:200, hidden:true },{ header:"项目编号", dataIndex:"xmid", width:200, hidden:true, editor:new Ext.form.TextField({ id:"costXmid" }) },{ header:"支出内容(经济科目)", dataIndex:"subject", width:200, sortable:true, editor:new Ext.form.TextField({ allowBlank: false }) },{ header:"计划支出数", dataIndex:"planCost", width:200, sortable:true, editor:new Ext.form.TextField({ allowBlank: false }) },{ header:"实际支出数", dataIndex:"actualCost", width:200, sortable:true, editor:new Ext.form.TextField({ allowBlank: false }) } ] }); /*4.创建表格面板*/ var costGrid = new Ext.grid.EditorGridPanel({ cm:cm, store:costStore, clicksToEdit:1, loadMask:{msg:'正在加载数据,请稍侯……'}, height:480, width:600, tbar:[ { text:"保存", iconCls:"save", handler:saveCost },{ text:"增加", iconCls:"add", handler:function(){ var newCost = new costRecord({ id:-1, //id为-1,数据传到后台时,则可判断id,若为-1,则执行插入,若不为-1,则执行更新 xmid:Ext.getCmp("costXmid").getValue(), subject:'', subjectId:'', planCost:'', actualCost:'' }); costGrid.stopEditing(); //关闭表格的编辑状态 costStore.add(newCost); //store.insert(0, newCost); //创建的Record插入store的第一行 //store.insert(store.getCount(), newCost); //创建的Record插入store的最后一行 costGrid.startEditing(0, 0); //激活第一行第一列的编辑状态 } },{ text:"删除", iconCls:"remove", handler:removeCost } ] }); /*创建收支明细窗口*/ var costWin = new Ext.Window({ title:"收支明细", frame:"fit", closeAction:"hide", modal:true, items:costGrid });注意:
1.此处使用的是可编辑的表格面板
2.因为ColumnModel不能通过Ext.getCmp()取值赋值,此处给加了一个editor,增加一个TextField
这样子,就可以从通过点击链接,然后调用方法传递参数,把上一个表格面板的xmid传递到这个表格面板对应的xmid单元格中!!!
2.因为ColumnModel不能通过Ext.getCmp()取值赋值,此处给加了一个editor,增加一个TextField
这样子,就可以从通过点击链接,然后调用方法传递参数,把上一个表格面板的xmid传递到这个表格面板对应的xmid单元格中!!!
此时,在面板的方法中,也可通过Ext.getCmp()方式取值。
调用某个自定义的function(),可以直接用方法名!
调用某个自定义的function(),可以直接用方法名!
3.增加保存收支信息的方法
/*创建保存收支明细方法,只保存修改过的信息*/ function saveCost(){ //只提交修改过的记录 var rcds = costStore.getModifiedRecords(); if(rcds&&rcds.length>0){ Ext.Msg.wait("正在保存..."); var rows=new Array(); for(var i=0;i<rcds.length;i++){ var rs = rcds[i]; var row=new Object(); var fields=rs.data; row = {id:fields.id,xmid:fields.xmid,subject:fields["subject"],planCost:fields["planCost"],actualCost:fields["actualCost"]}; rows.push(row); } Ext.Ajax.request({ url: 'updateProjectCost.eva?doType=updateProjectCost', method:'POST', timeout:300000, success: result, failure: function(){Ext.Msg.alert('信息','未成功提交数据!'); }, params:{updateSets :Ext.encode(rows)} }); function result(response, options){ var result = Ext.util.JSON.decode(response.responseText); if(result.success){ Ext.Msg.hide(); Ext.Msg.show({title:'成功', msg: '数据保存成功', buttons: Ext.Msg.OK, icon: Ext.MessageBox.INFO}); //保存成功后刷新修改过的脏数据。 costStore.rejectChanges(); costStore.reload(); }else{ Ext.Msg.hide(); Ext.Msg.alert('信息','保存数据未成功!'); } } } }
注意:
1.js中集合即数组,遍历时,只能遍历 obj.length, 而不能遍历 obj.size()
2.遍历到下标 i 时,取下标 i 对应的值,只能用 obj[i], 不能用 obj.get(i)
(注意:此处是getModifiedRecords,得到的是一个数组!!!)
(如果是用store.data获得到的一个Records,则不是数组,不能用上面的方式,得用records.get(i)!!!)
3.js中的*父类是 object, 即所有对象都是 object, 但是取值跟java不同,
只能是 obj.name 或 obj["name"], 而不能用obj.get("name")!!!
具体可查看:http://blog.163.com/wumingli456@126/blog/static/2889641420101333142939/
4.修正:给表格面板添加复选框
/*3.创建列*/ var sm = new Ext.grid.CheckboxSelectionModel({ //singleSelect:true, //是否单选 handleMouseDown:Ext.emptyFn //若有该项,则单击行不选中,只有单击复选框才能选中 }); /*sm.singleSelect = true; sm.handleMouseDown = Ext.emptyFn;*/ //第二种写法 var cm = new Ext.grid.ColumnModel({ columns:[ sm, //1.现在columnModel中添加SelectionModel { header:"编号", dataIndex:"id", width:200, hidden:true },{ header:"项目编号", dataIndex:"xmid", width:200, hidden:true, editor:new Ext.form.TextField({ id:"costXmid" }) },{ header:"支出内容(经济科目)", dataIndex:"subject", width:200, sortable:true, editor:new Ext.form.TextField({ allowBlank: false }) },{ header:"计划支出数", dataIndex:"planCost", width:200, sortable:true, editor:new Ext.form.TextField({ allowBlank: false }) },{ header:"实际支出数", dataIndex:"actualCost", width:200, sortable:true, editor:new Ext.form.TextField({ allowBlank: false }) } ] }); /*4.创建表格面板*/ var costGrid = new Ext.grid.EditorGridPanel({ cm:cm, sm:sm, ////2.再在GridPanel中添加SelectionModel store:costStore, clicksToEdit:1, stripeRows: true, loadMask:{msg:'正在加载数据,请稍侯……'}, height:480, width:600, tbar:[ { text:"保存", iconCls:"save", handler:saveCost },{ text:"增加", iconCls:"add", handler:function(){ var newCost = new costRecord({ id:-1, //id为-1,数据传到后台时,则可判断id,若为-1,则执行插入,若不为-1,则执行更新 xmid:Ext.getCmp("costXmid").getValue(), subject:'', subjectId:'', planCost:'', actualCost:'' }); costGrid.stopEditing(); //关闭表格的编辑状态 costStore.add(newCost); //store.insert(0, newCost); //创建的Record插入store的第一行 //store.insert(store.getCount(), newCost); //创建的Record插入store的最后一行 costGrid.startEditing(0, 0); //激活第一行第一列的编辑状态 } },{ text:"删除", iconCls:"remove", handler:removeCost } ] });
注意:
1.创建的CheckboxSelectionModel必须在ColumnModel和GridPanel中都添加!
2.表格增加一行空行时的注意事项:
5.添加勾选复选框进行删除的方法
/*创建删除收支信息的方法,删除复选框勾选的记录*/ function removeCost(){ var rcs = costGrid.getSelectionModel().getSelections(); if(!rcs||rcs.length<1){ Ext.Msg.alert("提示","请先选择要删除的行"); return; } else{ Ext.Msg.confirm("确认删除","请确认是否删除选中的项目支出条目?",function(btn){ if(btn == "yes"){//选中"是"的按钮 var ids = new Array(); for (var i = 0; i < rcs.length; i++) { ids.push(rcs[i].get("id")); } //异步发请求 Ext.Ajax.request({ url:"deleteCosts.eva?doType=deleteCosts", method:"POST", params:{costIds:ids.join(",")}, success:function(response,option){ var result = Ext.util.JSON.decode(response.responseText); if (result.success) { Ext.Msg.alert("删除成功","选中的项目支出条目已成功删除!"); costStore.rejectChanges(); costStore.reload(); } }, failure:function(response,option){ Ext.Msg.alert("删除失败","删除过程中发生错误!"); } }); } }); } }注意:
Js中obj取值不能用get,而Extjs中取值可以用get。
如下所示:此处 rcs 是Ext中的sm,类似record,可用get取值。
Js中通过数组的 join("separate")来把数据合并成一个字符串,然后在java后台通过string.split("separate")分割
else if("deleteCosts".equals(action)){ String ids = request.getParameter("costIds"); ProjectCostDao costDao = new ProjectCostDao(); boolean done = costDao.deleteCosts(ids); String str =null; if(done){ str="{success:true}"; }else{ str="{success:false}"; } response.setContentType("text/html;charset=UTF-8"); out=response.getWriter(); out.print(str); out.close(); return; }
/** * 通过传入的id删除支出记录 * @param idss * @return */ public boolean deleteCosts(String idss) { Session s = null; boolean done = false; List<Integer> ids = new ArrayList<Integer>(); String[] costIds = idss.split(","); for (int i = 0; i < costIds.length; i++) { ids.add(Integer.valueOf(costIds[i])); } try { s = HibernateUtil.getSession(); s.beginTransaction(); StringBuffer sb = new StringBuffer("delete from project_cost where id in("); for (int i = 0; i < ids.size(); i++) { sb.append(ids.get(i)); if (i != ids.size() -1) { sb.append(","); } } sb.append(")"); Query query = s.createSQLQuery(sb.toString()); query.executeUpdate(); s.getTransaction().commit(); done = true; } catch (Throwable e) { logger.error(e.toString()); HibernateUtil.endSession(s); } finally { HibernateUtil.endSession(s); } return done; }