`

Ext Grid Form 增删改例子

    博客分类:
  • Ext
阅读更多

转载自:http://www.cnblogs.com/Missing1984/archive/2008/09/26/1299684.html

写的比较详细;尤其是客户端js代码.参考了

----------------------------------------------------------------------

框架是 Extjs+Structs2+Spring+Hibernate 直接调用action获取数据和保存

页面JS代码如下


JsonReader和Dataproxy定义

2张表 一张Userinfo 一张Departmentinfo  Departmentinfo 用来填充表单的ComboBox
    var Userreader = new Ext.data.JsonReader({
        totalProperty: "totalSize",
        root: "data"
    },
    Ext.data.Record.create([{
        name: "UserID",
        type: "string"
    },
    {
        name: "UserName",
        type: "string"
    },
    {
        name: "UserPassword",
        type: "string"
    },
    {
        name: "RoleList",
        type: "string"
    },
    {
        name: "FuncList",
        type: "string"
    },
    {
        name: "Sex",
        type: "string"
    },
    {
        name: "WenHua",
        type: "string"
    },
    {
        name: "Age",
        type: "int"
    },
    {
        name: "Email",
        type: "string"
    },
    {
        name: "Telephone",
        type: "string"
    },
    {
        name: "Cellphone",
        type: "string"
    },
    {
        name: "ShortName",
        type: "string"
    },
    {
        name: "DepID",
        type: "int"
    }]));

    var Deptreader = new Ext.data.JsonReader({
        totalProperty: "totalSize",
        root: "data"
    },
    Ext.data.Record.create([{
        name: "DepID",
        type: "int"
    },
    {
        name: "DepCode",
        type: "string"
    },
    {
        name: "DepName",
        type: "string"
    },
    {
        name: "Comment",
        type: "string"
    }]));

    var Usercolumns = [{
        "header": "UserID",
        "dataIndex": "UserID",
        "sortable": "true",
        "id": "UserID"
    },
    {
        "header": "UserName",
        "dataIndex": "UserName",
        "sortable": "true",
        "id": "UserName"
    },
    {
        "header": "UserPassword",
        "dataIndex": "UserPassword",
        "sortable": "true",
        "id": "UserPassword"
    },
    {
        "header": "RoleList",
        "dataIndex": "RoleList",
        "sortable": "true",
        "id": "RoleList"
    },
    {
        "header": "FuncList",
        "dataIndex": "FuncList",
        "sortable": "true",
        "id": "FuncList"
    }];
    var Userproxy = new Ext.data.HttpProxy({
        url: 'GetUserList.action'
    });

    var Userstore = new Ext.data.Store({
        proxy: Userproxy,
        reader: Userreader
    });

    var Deptproxy = new Ext.data.HttpProxy({
        url: 'GetDeptList.action'
    });

    var Deptstore = new Ext.data.Store({
        proxy: Deptproxy,
        reader: Deptreader
    });


GridPanel

var UserMgrPn = new Ext.grid.GridPanel({
        title: '用户管理',
        closable: true,
        store: Userstore,
        columns: Usercolumns,
        tbar: [{
            pressed: true,
            text: 'Add',
            handler: doAddUser
        },

        //加上这句,后面的就显示到右边去了
        {
            pressed: true,
            text: "Edit",
            handler: doEditUser
        },
        {
            pressed: true,
            text: "Delete",
            handler: doDelUser
        }]
    });


增删改事件,试验代码
var doAddUser = function() {
        var simpleForm = new Ext.FormPanel({
            labelWidth: 75,
            // label settings here cascade unless overridden
            frame: true,
            title: 'User Info',
            bodyStyle: 'padding:5px 5px 0',
            width: 350,
            defaults: {
                width: 230
            },
            defaultType: 'textfield',
            items: [{
                fieldLabel: 'UserID',
                name: 'UserID'
            },
            {
                fieldLabel: 'UserName',

                name: 'UserName'
            },
            {
                fieldLabel: 'UserPassword',
                name: 'UserPassword'
            },
            {
                fieldLabel: 'RoleList',
                name: 'RoleList'
            },
            {
                fieldLabel: 'FuncList',
                name: 'FuncList'
            },
            {
                fieldLabel: 'Sex',
                name: 'Sex'
            },
            new Ext.form.ComboBox({
                fieldLabel: 'Department',
                hiddenName: 'DepID',
                store: Deptstore,
                valueField: 'DepID',
                displayField: 'DepName',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText: 'Select a department',
                selectOnFocus: true
            })],
            buttons: [{
                text: 'Save',
                handler: function() {
                    if (simpleForm.form.isValid()) {
                        simpleForm.form.doAction('submit', {
                            url: 'EditUserSave.action?action=add',
                            method: 'post',
                            params: '',
                            success: function(form, action) {
                                Ext.Msg.alert('success', action.result.info);

                                Userstore.load();
                                newFormWin.hide();
                            },
                            failure: function() {
                                Ext.Msg.alert('fail', 'notice');

                            }
                        });
                    }
                }
            },
            {
                text: 'Cancel'
            }]
        });
        var myFormWin = function() {
            // create the window on the first click and reuse on subsequent
            // clicks

            newFormWin = new Ext.Window({
                layout: 'fit',
                width: 400,
                height: 300,
                plain: true,
                title: '',
                items: simpleForm
            });
            newFormWin.show('New1');
        };
        myFormWin();
        Deptstore.load();
    };

    var doEditUser = function() {
        var simpleForm = new Ext.FormPanel({
            labelWidth: 75,
            // label settings here cascade unless overridden
            frame: true,
            title: 'User Info',
            bodyStyle: 'padding:5px 5px 0',
            width: 350,
            reader: Userreader,
            defaults: {
                width: 230
            },
            defaultType: 'textfield',
            items: [{
                fieldLabel: 'UserID',
                name: 'UserID'
            },
            {
                fieldLabel: 'UserName',

                name: 'UserName'
            },
            {
                fieldLabel: 'UserPassword',

                name: 'UserPassword'
            },
            {
                fieldLabel: 'RoleList',
                name: 'RoleList'
            },
            {
                fieldLabel: 'FuncList',
                name: 'FuncList'
            },
            {
                fieldLabel: 'Sex',
                name: 'Sex'
            },
            new Ext.form.ComboBox({
                fieldLabel: 'Department',
                hiddenName: 'DepID',
                store: Deptstore,
                valueField: 'DepID',
                displayField: 'DepName',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText: 'Select a department',
                selectOnFocus: true
            })],
            buttons: [{
                text: 'Save',
                handler: function() {
                    if (simpleForm.form.isValid()) {

                        simpleForm.form.doAction('submit', {
                            url: 'EditUserSave.action?action=edit',
                            method: 'post',
                            params: '',
                            success: function(form, action) {
                                Ext.Msg.alert('success', action.result.info);

                                Userstore.load();
                                newFormWin.hide();
                            },
                            failure: function() {
                                Ext.Msg.alert('fail', 'notice');

                            }
                        });
                    }
                }
            },
            {
                text: 'Cancel'
            }]
        });
        var myFormWin = function() {
            // create the window on the first click and reuse on subsequent
            // clicks

            newFormWin = new Ext.Window({
                layout: 'fit',
                width: 400,
                height: 300,
                plain: true,
                title: '',
                items: simpleForm
            });
            newFormWin.show('New1');
        };

        var _record = UserMgrPn.getSelectionModel().getSelected();
        if (!_record) {
            Ext.Msg.alert('修改操作', '请选择要修改的一项!');
        } else {
            myFormWin();
            Deptstore.load();
            simpleForm.form.load({
                url: 'EditUserLoad.action?UserID=' + _record.get('UserID'),
                waitMsg: '正在载入数据',
                failure: function(form, action) {
                    Ext.Msg.alert('编辑', '载入失败');
                }
            });
        }
    };

    var doDelUser = function() {
        var _record = UserMgrPn.getSelectionModel().getSelected();
        if (!_record) {
            Ext.Msg.alert('删除操作', '请选择要删除的一项!');
        } else {
            Ext.Msg.confirm('确认', '真的要删除吗?',
            function(btn) {
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        url: 'EditUserSave.action?action=del&UserID=' + _record.get('UserID'),
                        success: function(result) {   Ext.Msg.alert('Result', '删除成功!');
                            Userstore.load();
                        }
                    });
                }
            });
        }
    };


后台Java代码如下

UserService
public class UserService extends BaseAction {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String UserID;
    private String UserName;
    private String UserPassword;
    private String RoleList;
    private String FuncList;
    private Integer sex;
    private String wenHua;
    private Integer age;
    private String shortName;
    private String email;
    private String telphone;
    private String cellphone;
    private Integer DepID;
    private UserinfoDAO userdao;

    @SuppressWarnings("unchecked")
    public String GetUserList() throws IOException {
        Iterator ir = userdao.findAll().iterator();
        List list = new ArrayList();

        while (ir.hasNext()) {
            Userinfo user = (Userinfo) ir.next();
            Map<String, Object> row = new HashMap<String, Object>();
            row.put("UserID", user.getUserId());
            row.put("UserName", user.getUserName());
            row.put("UserPassword", user.getUserPassword());
            row.put("RoleList", user.getRoleList());
            row.put("FuncList", user.getFuncList());
            row.put("Sex", user.getSex());
            row.put("WenHua", user.getWenHua());
            row.put("Age", user.getAge());
            row.put("ShortName", user.getShortName());
            row.put("Email", user.getEmail());
            row.put("Telphone", user.getTelphone());
            row.put("CellPhone", user.getCellphone());
            list.add(row);
        }

        HashMap map = new HashMap();
        map.put("totalSize", list.size());
        map.put("data", list);
        JSONObject jSon = new JSONObject(map);
        getResponse().setContentType("text/json; charset=utf-8");
        getResponse().getWriter().write(jSon.toString());
        System.out.println(jSon.toString());
        return null;
    }

    public String GetOneUser() throws IOException {
        String userID = getRequest().getParameter("UserID");
        Userinfo user = userdao.findById(userID);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> row = new HashMap<String, Object>();
        row.put("UserID", user.getUserId());
        row.put("UserName", user.getUserName());
        row.put("UserPassword", user.getUserPassword());
        row.put("RoleList", user.getRoleList());
        row.put("FuncList", user.getFuncList());
        row.put("Sex", user.getSex());
        row.put("WenHua", user.getWenHua());
        row.put("Age", user.getAge());
        row.put("ShortName", user.getShortName());
        row.put("Email", user.getEmail());
        row.put("Telphone", user.getTelphone());
        row.put("CellPhone", user.getCellphone());
        row.put("DepID", user.getDeptID());
        list.add(row);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("totalSize", list.size());
        map.put("data", list);
        JSONObject jSon = new JSONObject(map);
        getResponse().setContentType("text/json; charset=utf-8");
        getResponse().getWriter().write(jSon.toString());
        System.out.println(jSon.toString());
        return null;
    }

    public String SaveUser() throws IOException {
        if (getRequest().getParameter("action").equals("edit")) {
            Userinfo edituser = userdao.findById(UserID);
            edituser.setUserId(UserID);
            edituser.setUserName(UserName);
            edituser.setUserPassword(UserPassword);
            edituser.setRoleList(RoleList);
            edituser.setFuncList(FuncList);
            edituser.setDeptID(DepID);
            userdao.getHibernateTemplate().update(edituser);
            getResponse().getWriter().write("{success:true,info:'success'}");
        } else if (getRequest().getParameter("action").equals("add")) {
            Userinfo edituser = new Userinfo();
            edituser.setUserId(UserID);
            edituser.setUserName(UserName);
            edituser.setUserPassword(UserPassword);
            edituser.setRoleList(RoleList);
            edituser.setFuncList(FuncList);
            edituser.setDeptID(DepID);
            userdao.getHibernateTemplate().save(edituser);
            getResponse().getWriter().write("{success:true,info:'success'}");
        } else if (getRequest().getParameter("action").equals("del")) {
            String userID = getRequest().getParameter("UserID");
            Userinfo deluser = userdao.findById(userID);
            userdao.delete(deluser);
            getResponse().getWriter().write("{success:true,info:'success'}");
        }
        return null;
    }

    public UserinfoDAO getUserdao() {
        return userdao;
    }

    public void setUserdao(UserinfoDAO userdao) {
        this.userdao = userdao;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getWenHua() {
        return wenHua;
    }

    public void setWenHua(String wenHua) {
        this.wenHua = wenHua;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelphone() {
        return telphone;
    }

    public void setTelphone(String telphone) {
        this.telphone = telphone;
    }

    public String getCellphone() {
        return cellphone;
    }

    public void setCellphone(String cellphone) {
        this.cellphone = cellphone;
    }

    public String getUserID() {
        return UserID;
    }

    public void setUserID(String userID) {
        UserID = userID;
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getUserPassword() {
        return UserPassword;
    }

    public void setUserPassword(String userPassword) {
        UserPassword = userPassword;
    }

    public String getRoleList() {
        return RoleList;
    }

    public void setRoleList(String roleList) {
        RoleList = roleList;
    }

    public String getFuncList() {
        return FuncList;
    }

    public void setFuncList(String funcList) {
        FuncList = funcList;
    }

    public Integer getDepID() {
        return DepID;
    }

    public void setDepID(Integer depID) {
        DepID = depID;
    }
}


Department
package com.newsoft.struts.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.newsoft.superOA.PO.*;
import com.newsoft.superOA.Util.JSONObject;

public class DeptService extends BaseAction {

    private Integer depId;
    private String depCode;
    private String depName;
    private String comment;
    private DepartmentinfoDAO depdao;
    
    public String GetDeptList() throws IOException {
        Iterator ir = depdao.findAll().iterator();
        List list = new ArrayList();

        while (ir.hasNext()) {
            Departmentinfo dept = (Departmentinfo) ir.next();
            Map<String, Object> row = new HashMap<String, Object>();
            row.put("DepID", dept.getDepId());
            row.put("DepCode", dept.getDepCode());
            row.put("DepName",dept.getDepName());
            row.put("Comment", dept.getComment());
            list.add(row);
        }
        HashMap map = new HashMap();
        map.put("totalSize", list.size());
        map.put("data", list);
        JSONObject jSon = new JSONObject(map);
        getResponse().setContentType("text/json; charset=utf-8");
        getResponse().getWriter().write(jSon.toString());
        System.out.println(jSon.toString());
        return null;
    }

    public Integer getDepId() {
        return depId;
    }

    public void setDepId(Integer depId) {
        this.depId = depId;
    }

    public String getDepCode() {
        return depCode;
    }

    public void setDepCode(String depCode) {
        this.depCode = depCode;
    }

    public String getDepName() {
        return depName;
    }

    public void setDepName(String depName) {
        this.depName = depName;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public DepartmentinfoDAO getDepdao() {
        return depdao;
    }

    public void setDepdao(DepartmentinfoDAO depdao) {
        this.depdao = depdao;
    }
}

分享到:
评论

相关推荐

    Ext表格中增删改查实例

    本文将深入探讨如何在Ext Grid中实现增删改查(CRUD)操作,这些操作是任何数据管理应用的基础。 首先,我们需要了解`Ext.grid.Panel`,它是Ext JS中的主要表格组件。这个组件可以显示大量数据,并提供了分页、排序...

    extjs 增删改查

    `Ext.grid.Panel`是用于展示表格数据的主要组件,它可以与后台数据库进行交互。在这个场景中,我们可能会使用`Ext.data.Store`来存储和管理数据,该Store会连接到一个数据源,例如通过Ajax请求获取JSON格式的数据。 ...

    extJs 简单的增删改查

    2. **创建存储(Store)**:存储数据,并与模型关联,处理数据的加载、增删改操作。 ```javascript var store = Ext.create('Ext.data.Store', { model: 'User', data: [{ id: 1, name: 'Alice', email: 'alice@...

    Ext+Jsp+Hibernate 学生信息管理

    Ext+Jsp+Hibernate 学生信息管理 使用Ext做界面,Jsp负责转发页面,Hibernate负责数据...实现了数据列表及分页显示,数据的增删改,及grid与form的联动效果。 开发平台:WinXP+Tomcat6+MyEclipse6+SQLServer2005+Spket

    ExtJs GridPanel简单的增删改实现代码

    在init函数中,我们首先创建一个表单Ext.form.FormPanel,用于收集新增角色时所需填写的信息。表单中可以定义多个字段,例如角色名称(RoleName),并且通过ExtJs的验证机制确保用户填写的数据符合要求。 之后,...

    Ext Js权威指南(.zip.001

    Ex4.0共2个压缩包特性,《ext js权威指南》 ...10.3.4 数据汇总功能:ext.grid.featrue.abstractsummary与ext.grid.featrue. summary / 539 10.3.5 分组功能:ext.grid.featrue.grouping / 543 10.3.6 分组汇总...

    extjs做的增删改查

    当用户在Grid或Form中进行操作时,触发相应的事件,Controller接收到事件后调用Store的相应方法,如load、add、remove、update。 8. **远程数据操作**:通常,增删改查操作会涉及到服务器端的数据交互。ExtJS支持...

Global site tag (gtag.js) - Google Analytics