天天看点

EXT可编辑Grid(EditorGridPanel )实现增删改

Ext.onReady(function() {
    Ext.BLANK_IMAGE_URL = '../resources/images/default/s.gif';

    Ext.QuickTips.init();

    function formatDate(value) {
    	//var date = new Date(value);
    	return value ? date.dateFormat('Y-m-d H:i:s') : '';
    }

    var sm = new Ext.grid.CheckboxSelectionModel({checkOnly : true});

    var cm = new Ext.grid.ColumnModel([sm, {
		        id : 'ID',
		        header : '编号',
		        dataIndex : 'ID',
		        align : 'center',
		        width : 110,
		        hidden : true
    		}, {
		        header : '名称',
		        dataIndex : 'name',
		        align : 'center',
		        width : 150,
		        editor : new Ext.form.TextField({})
    		}, {
		        header : "时间",
		        dataIndex : 'time',
		        width : 120,
		        align : 'center',
		        renderer : formatDate,
		        editor : new Ext.ux.form.DateTimeField({
		            fieldLabel : '时间',
		            id : 'time',
		            name : 'time',
		            width : 130,
		            height : 30,
		            allowBlank : false,
		            blankText : '时间不能为空',
		            editable : false,
		            value : new Date()
				})
    		}]);

    var record = Ext.data.Record.create([{
		        name : 'ID',
		        type : 'string'
    		}, {
		        name : 'name',
		        type : 'string'
    		}, {
		        name : 'time',
		        type : 'date',
		        dateFormat : 'Y-m-d H:i:s'
    		}]);

    var store = new Ext.data.Store({
	        autoLoad : false,
	        pruneModifiedRecords : true, //每次Store加载后,清除所有修改过的记录信息	
	        proxy : new Ext.data.HttpProxy({
	            url : 'list.action',
	            method : 'POST'
	        }),
	        baseParams : {
	        	pageNo : 0,
	        	pageSize : 10
	        },
	        paramNames : {
	        	start : "pageNo",
	        	limit : "pageSize"
	        },
	        reader : new Ext.data.JsonReader({
		            totalProperty : 'totalCount',
		            root : 'results'
	        	}, record)
	    	});

    store.load();

    var tbar = new Ext.Toolbar({
        	items : [{
	            text : '新增',
	            iconCls : 'add',
	            handler : add
    		}, '-', {
	            text : '保存',
	            iconCls : 'save',
	            handler : save
    		}, '-', {
	            text : '删除',
	            iconCls : 'remove',
	            handler : remove
    		}]
    	});

    var bbar = new Ext.PagingToolbar({
	        pageSize : 10,
	        store : store,
	        displayInfo : true,
	        lastText : "尾页",
	        nextText : "下一页",
	        beforePageText : "当前",
	        prevText : "上一页",
	        firstText : "首页",
	        refreshText : "刷新",
	        afterPageText : "页,共{0}页",
	        displayMsg : '数据从第{0}条 - 第{1}条 共{2}条数据',
	        emptyMsg : '没有数据'
    	});

    var grid = new Ext.grid.EditorGridPanel({
	        id : "myGrid",
	        title : '信息维护', 
	        renderTo : 'grid', 
	        sm : sm,
	        cm : cm,
	        store : store,
	        clicksToEdit : 1,
	        loadMask : {
	        	msg : '正在加载数据,请稍侯……'
	        },
	        autoScroll : true,
	        autoWidth : true,
	        autoHeight : true,
	        stripeRows : true,
	        viewConfig : {
	        	forceFit : true
	        },
	        tbar : tbar,
	        bbar : bbar
    	});

    grid.render();

    function add() {
    	var initValue = {
    		ID : "",
    		name : "",
    		time : new Date()
    	};
    	var recode = store.recordType;
    	var p = new recode(initValue); // 根据上面创建的recode 创建一个默认值
    	grid.stopEditing();
    	store.insert(0, p);// 在第一个位置插入
    	grid.startEditing(0, 1);// 指定的行/列,进行单元格内容的编辑
    }

    function save() {
    	var modified = store.modified;
		Ext.Msg.confirm("警告", "确定要保存吗?", function(button) {
        	if (button == "yes") {
        		var json = [];
        		Ext.each(modified, function(item) {
            		json.push(item.data);
            	});
        		if (json.length > 0) {
		            Ext.Ajax.request({
		                url : "save.action",
		                params : {
		                	data : Ext.util.JSON.encode(json)
		                },
		                method : "POST",
		                success : function(response) {
		                	Ext.Msg.alert("信息","数据保存成功!",function() {
		                    	store.reload();
		                    });
		                },
		                failure : function(response) {
		                	Ext.Msg.alert("警告","数据保存失败,请稍后再试!");
		                }
		            });
        		} else {
            		Ext.Msg.alert("警告", "没有任何需要更新的数据!");
        		}
        	}
        });
    }

    function remove() {
    	var selModel = grid.getSelectionModel();
    	if (selModel.hasSelection()) {
    		Ext.Msg.confirm("警告", "确定要删除吗?", function(button) {
        		if (button == "yes") {
		            var recs = selModel.getSelections();
		            var list = [];
		            for (var i = 0; i < recs.length; i++) {
		            	var rec = recs[i];
		            	list.push("'" + rec.get('ID') + "'");
		            }
		            Ext.Ajax.request({
		                url : "delete.action",
		                params : {
		                	data : list.join(',')
		                },
		                method : "POST",
		                success : function(response) {
		                	Ext.Msg.alert("信息","数据删除成功!", function() {
		                    	store.reload();
		                    });
		                },
		                failure : function(response) {
		                	Ext.Msg.alert("警告","数据删除失败,请稍后再试!");
		                }
		            });
        		}
        	});
    	} else {
    		Ext.Msg.alert("错误", "没有任何行被选中,无法进行删除操作!");
    	}
    }
});
           

后台:

public String list() throws Exception {
		String sql = "select ID,name,time from Info";
		String rs= infoService.getJSONBySQL(sql, page);
		String jsonString = "{totalCount:" + page.getTotal() + ",results:" + rs+ "}";

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().print(jsonString);

		return null;
	}

	public String save() throws Exception {
		String data = request.getParameter("data");
		JSONArray array = JSONArray.fromObject(data);
		Object[] list = array.toArray();
		for (int i = 0; i < list.length; i++) {
			Map<String, String> map = (Map<String, String>) list[i];
			Info info = new Info();
			info.setId(map.get("ID"));
			info.setName(map.get("name"));
			info.setTime(map.get("time"));

			if (null != info.getId() && info.getId().length() > 0) {
				infoService.upate(info);
			} else {
				infoService.save(info);
			}
		}

		response.getWriter().write("SUCCESS");

		return null;
	}

	public String delete() throws Exception {
		String ids = request.getParameter("data");

		infoService.delete(ids);

		response.getWriter().write("SUCCESS");

		return null;
	}