ExtJS EditorGridPanel 示例之Array格式(自定义Array解析器)Store前后台增删改查
最后更新于:2022-04-01 12:01:08
本示例入口html页面:
~~~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>用户数据编辑 用ArrayReader 实现分页</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<meta http-equiv="author" content="hoojo">
<meta http-equiv="email" content="hoojo_@126.com">
<meta http-equiv="blog" content="http://blog.csdn.net/IBM_hoojo">
<link rel="stylesheet" type="text/css" href="../ext2/resources/css/ext-all.css"></link>
<script type="text/javascript" src="../ext2/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../ext2/ext-all.js"></script>
<script type="text/javascript" src="../ext2/build/locale/ext-lang-zh_CN-min.js"></script>
<!-- 用ArrayReader 实现分页,需要改进ArrayReader 的代码 -->
<script type="text/javascript" src="ArrayReader.js"></script>
<script type="text/javascript" src="ArrayPagingEditorGridPanel.js"></script>
<script type="text/javascript">
Ext.onReady(function (){
Ext.QuickTips.init();
//Ext.form.Field.prototype.msgTarget = "side";
Ext.BLANK_IMAGE_URL = "../ext2/resources/images/default/s.gif";
new ArrayPagingEditorGridPanel();
});
</script>
</head>
<body>
</body>
</html>
~~~
ArrayPagingEditorGridPanel.js文件代码:
~~~
/**
* 用Array格式的数据形式:Ext.data.Store,自定义Ext.data.ArrayReader数组解析器,实现editorGrid的增删改查
* author: hoojo
* email: hoojo_@126.com
* blog: http://blog.csdn.net/IBM_hoojo
* ext-lib: v2.2
*/
/****************************************************************/
/*******ArrayPagingEditorGridPanel*******/
/****************************************************************/
ArrayPagingEditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
sexCombo: null,
inserted: [],
constructor: function () {
this.sexCombo = new Ext.form.ComboBox({
mode: "local",
value: "全部",
readOnly: true,
triggerAction: "all",
displayField: "sex",
//listAlign : "bl-tl", //下拉列表的显示方式 bl-tl是在上方显示,相反tl-bl是从下方显示
store: new Ext.data.SimpleStore({
data: ["男", "女", "全部"],
expandData: true,
fields: ["sex"]
}),
listeners: {
"select": {
fn: this.filterSex,
scope: this
}
}
});
this["store"] = new Ext.data.Store({
url: ArrayPagingEditorGridPanel.USER_STORE_URL,
reader: new Ext.data.ArrayReader({
id: "id", //维护当前数据的唯一性(和数据库主键类似,避免数据重复--过滤重复数据)
root: "users",
totalProperty: "totals"
},
Ext.data.Record.create(["id","name",
{name: "age", type: "int"}, "sex",
{name: "birthday", type: "date", dateFormat: "Y-m-d"}
])
),
sortInfo:{field:"name", direction:"ASC"} //排序
});
ArrayPagingEditorGridPanel.superclass.constructor.call(this, {
renderTo: Ext.getBody(),
width: 480,
height: 300,
frame: true,
stripeRows: true,
clicksToEdit: 2, //表示点击多少次数才可以编辑表格
collapsible: true, //是否在右上角显示收缩按钮
animCollapse: true, //表示收缩(闭合)面板时,显示动画效果
trackMouseOver: true, //鼠标在行上移动时显示高亮
enableColumnMove: false,//禁止用户拖动表头
autoExpandColumn: "name", //这里指定的name的id ,此属性可以根据当前列 填充空白区域
title: "用户数据编辑器",
tbar: [
"查看方式:",
this.sexCombo,
"-",
{
text: "保存数据",
handler: this.onCommitStore,
scope: this
}
],
bbar: [{
text: "添加数据",
handler: this.onAddClick,
scope: this
},"-",{
text: "删除数据",
handler: this.onRemoveClick,
scope: this
},new Ext.PagingToolbar({
pageSize: 5,
store: this.store
})],
columns:[{
id: "name",
header: "姓名",
align: "center",
dataIndex: "name",
editor: new Ext.form.TextField({
allowBlank: false,
blankText: "姓名不能为空,必须输入"
})
},{
header: "年龄",
align: "center",
dataIndex: "age",
editor: new Ext.form.NumberField({
allowBlank: false,
allowNegative: false, //只能为正数
//maxValue: 1000000000,
grow: true, //前半部分显示正在改的数据,后半部分显示以前的老数据
selectOnFocus: true, //当获得焦点时,选中所有的文本内容
minValue: 1
})
},{
header: "性别",
align: "center",
dataIndex: "sex",
editor: new Ext.form.ComboBox({
mode: "local",
value: "男",
readOnly: true,
displayField: "sex",
triggerAction: "all",
store: new Ext.data.SimpleStore({
data: ["男", "女"],
expandData: true,
fields: ["sex"]
})
})
},{
header: "生日",
align: "center",
sortable: true,
dataIndex: "birthday",
renderer: Ext.util.Format.dateRenderer('Y-m-d'),
editor: new Ext.form.DateField({
format: "Y-m-d",
minValue: "1950-01-01",
disabledDays: [0, 7],//datefield的第0列:周日和第7列:周六不能编辑
disabledDaysText: "周末不能选择"
})
}],
sm: new Ext.grid.RowSelectionModel({
singleSelect: true
})
});
this.store.load({params: {start: 0, limit: 5}});
/*Ext.Ajax.on("requestcomplete", function (conn, response, options) {
alert(response.responseText);
});*/
},
filterSex: function (cob) {
if (cob.getValue() == "全部"){
this.store.clearFilter();
}
else
this.store.filter("sex", cob.value);
},
onAddClick: function () {
var rs = new Ext.data.Record({id: "",name: "", age: 1, sex: "", birthday: 0000-00-00});
this.getStore().add(rs);
rs.set("name", "ext");
rs.set("age", 22);
rs.set("sex", "男");
rs.set("birthday", new Date());
this.inserted.push(rs);
this.startEditing(this.store.getCount() - 1, 0);
},
saveInsertData: function (conn, response) {
var xml = response.responseXML;
var root = xml.documentElement;
for (var i = 0; i < root.childNodes.length; i++) {
this.inserted[i].set("id", root.childNodes[i].text);
}
this.getStore().commitChanges();
this.inserted = [];
},
onCommitStore: function () {
var mf = this.getStore().modified;
var temp = [];
for (var i = 0; i < mf.length; i ++) {
if (mf[i].get("id") == ""){
continue;
}
var data = {};
for (var j in mf[i].modified) {
data[j] = mf[i].get(j);
}
temp.push(Ext.apply(data, {id: mf[i].get("id")}));
}
for (var i = 0; i < this.inserted.length; i ++) {
temp.push(this.inserted[i].data);
}
Ext.Ajax.on("requestcomplete", function (conn, response, options) {
alert(response.responseText);
});
//Ext.Ajax.on("requestcomplete", this.saveInsertData, this);
//想服务器发送请求,传递修改的数据(只含修改的数据)
Ext.Ajax.request({url: "../ServiceServlet?method=edit", params: {content:Ext.util.JSON.encode(temp)}});
this.store.commitChanges();
this.filterSex(this.sexCombo);
},
onRemoveClick: function () {
var rs = this.getSelectionModel();
try{
if (rs.getCount() == 0) {
Ext.Msg.alert("系统提示", "没有选定数据,请选择数据行!");
}else {
Ext.Msg.confirm("系统提示", "您确定要删除当前数据吗?", this.removeUserInfo, this);
}
}catch(er) {
Ext.Msg.alert("系统提示", er.discription);
}
},
removeUserInfo: function (btnText) {
if (btnText == "yes"){
var rs = this.getSelectionModel().getSelected();
this.getStore().remove(rs);
if (rs.get("id") != "") {
Ext.Ajax.on("requestcomplete", function (conn, response, options) {
if (response.responseText == "success") {
alert("success");
}else {
alert("failure");
}
});
Ext.Ajax.request({url: "../ServiceServlet?method=remove", params: {id:rs.get("id")}});
}else {
this.inserted.remove(rs);
//this.getStore().modified.romove(rs);
}
}
}
});
ArrayPagingEditorGridPanel.USER_STORE_URL = "http://localhost:8080/Demo3/ServiceServlet?method=arry";
~~~
后台java servlet交互代码:
~~~
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hoo.dao.IUser;
import com.hoo.dao.impl.UserDao;
import com.hoo.entity.UserInfo;
@SuppressWarnings({"unchecked", "serial"})
public class ServiceServlet extends HttpServlet {
private IUser dao = new UserDao();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
StringBuilder builder = new StringBuilder();
String method = request.getParameter("method");
if ("arry".equals(method)) {
int start = Integer.parseInt(request.getParameter("start"));
int limit = Integer.parseInt(request.getParameter("limit"));
Object[] obj = dao.loadUserInfo(start, limit);
List<UserInfo> list = (List<UserInfo>) obj[1];
builder.append("{totals:").append(obj[0]).append(",users:[");
for (int i = 0; i < list.size(); i++) {
UserInfo u = (UserInfo) list.get(i);
builder.append("[/"").append(u.getId())
.append("/",/"").append(u.getName())
.append("/",").append(u.getAge())
.append(",/"").append(u.getSex())
.append("/",/"").append(u.getBirthday())
.append("/"]");
if (i < list.size()-1) {
builder.append(",");
}
}
builder.append("]}");
out.write(builder.toString());
}
if ("edit".equals(method)) {
String content = request.getParameter("content");
out.print(content);
}
if ("remove".equals(method)) {
Integer id = Integer.parseInt(request.getParameter("id"));
if (dao.removeUserInfo(id)) {
out.print("success");
}else {
out.print("failure");
}
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
~~~
本示例用ArrayReader解析数组数据分页,需要扩展原有的ArrayReader.js文件,下面是扩展文件:
~~~
Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
readRecords : function(o){
var sid = this.meta ? this.meta.id : null;
var recordType = this.recordType, fields = recordType.prototype.fields;
var records = [];
var root = this.meta ? this.meta["root"] ? o[this.meta["root"]] : o : o;
for(var i = 0; i < root.length; i++){
var n = root[i];
var values = {};
var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
for(var j = 0, jlen = fields.length; j < jlen; j++){
var f = fields.items[j];
var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
var v = n[k] !== undefined ? n[k] : f.defaultValue;
v = f.convert(v, n);
values[f.name] = v;
}
var record = new recordType(values, id);
record.json = n;
records[records.length] = record;
}
return {
records : records,
totalRecords : this.meta ? this.meta["totalProperty"] ? o[this.meta["totalProperty"]] : records.length : records.length
};
}
});
~~~
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-01_56fe122719c44.gif)
本示例最大的不同就是采用数据传递形式不同,用到的是Array格式。但ext v2.2版本中的ArrayReader结合Ext.data.Store
不支持分页,所以本示例进行扩展ArrayReader文件。