博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ExtJsCRUD组件实现
阅读量:6651 次
发布时间:2019-06-25

本文共 13462 字,大约阅读时间需要 44 分钟。

hot3.png

Crud组件实现:

/** * 定义命名空间 */Ext.namespace("Ext.darkness");/* *CRUD面板基类,继承自EXT的Panel */Ext.darkness.CrudPanel = Ext.extend(Ext.Panel, {        /**      *基本属性      */    gridPanel:null,    gridPanelId: 'gridPanel' + this.ID,    gridViewConfig: {},    cm: new Ext.grid.CheckboxSelectionModel(),    sm: new Ext.grid.CheckboxSelectionModel({		dataIndex: this.ID	}),//-列选择模式    store: null,    storeMapping: null,    pageSize: null,        keywordText: null,        baseUrl: null,        width: 800,    height: 600,      //构造器    constructor: function(config){                config = config || {};        this.pageSize = config.pageSize || 10;                this.keywordText = new Ext.form.TextField({            name: 'keyword',            anchor: '95%',            maxLength: 25        });                var flag = this.store == null;        if(flag){            this.store = new Ext.data.JsonStore({                id: this.ID,                url: this.baseUrl + '?cmd=List',//默认的数据源地址,继承时需要提供                root: "data",                totalProperty: "totalCount",                remoteSort: true,                fields: this.storeMapping            });        }                 this.cm.defaultSortable = true;                var viewConfig = Ext.apply({            forceFit: true        }, this.gridViewConfig);                this.gridPanel = new Ext.grid.GridPanel({            id: Ext.id(),            store: this.store,            cm: this.cm,            sm: this.sm,            trackMouseOver: false,            loadMask: true,            //超过长度带自动滚动条		    autoScroll:true,		    border:false,		    collapsible: true,            animCollapse: false,            viewConfig: viewConfig,            listeners: {                'celldblclick': {//双击时执行修改                    fn: this.onEdit,                    scope: this                },                'contextmenu':function(e) {                    e.stopEvent();                }            },            tbar: [{                id: 'addButton',                text: '添加',                iconCls: 'addicon',                tooltip: '添加新纪录',                handler: this.create,                scope: this            }, '-',//'-'给工具栏按钮之间添加'|'            {                id: 'editButton',                text: '编辑',                iconCls: 'editicon',                tooltip: '修改记录',                handler: this.onEdit,                scope: this            }, '-', {                text: '删除',                iconCls: 'deleteicon',                tooltip: '删除所选中的信息',                handler: this.onRemove,                scope: this            }, '-', {                text: '刷新',                iconCls: 'refreshicon',                tooltip: '刷新纪录',                handler: this.onRefresh,                scope: this            }, '->',//'->'代表让工具栏按钮到右边去            'Search: ', this.keywordText, {                text: '查询',                pressed: true,                iconCls: 'serchopenroomrecord',                handler: this.onSearch,                scope: this            }, '   '],            //分页            bbar: new Ext.PagingToolbar({                pageSize: this.pageSize,                store: this.store            })        });                //this.gridPanel.bbar = null;                if(this.view){            Ext.apply(this.gridPanel,{                view: this.view            });        }                this.store.load({            params: {                start: 0,                limit: this.pageSize            }        });                var configs = Ext.apply({            closable: true,            autoScroll: true,            layout: "fit",            items:[this.gridPanel],            /**              *渲染数据              */            //链接            linkRenderer: function(v){                if (!v)                     return "";                else                     return String.format("
{0}", v);            },            //时间            dateRender: function(format){                format = format || "Y-m-d h:i";                return Ext.util.Format.dateRenderer(format);            }        },config);                //调用父类的构造器        Ext.darkness.CrudPanel.superclass.constructor.call(this,configs);    },                  /**      *事件      */    //查询    onSearch: function(){        var keyword = this.keywordText.getValue();//得到输入框的值        this.store.load({            params: {                start: 0,                limit: 10,                keyword: keyword            }        });    },    //刷新    onRefresh: function(){        this.store.removeAll();        this.store.reload();    },    //初始化窗口(用于新增,修改时),继承后在createWin中调用该方法显示窗口    initWin: function(width, height, status){        var win = new Ext.Window({            title: "信息(" + status + ")",            width: width,            height: height,            modal: true,            shadow: true, iconCls:"addicon", //不可以随意改变大小 resizable:false, //是否可以拖动 //draggable:false, defaultType:"textfield", labelWidth:100, collapsible:true, //允许缩放条            closeAction : 'hide',            closable:true,            plain : true,            //弹出模态窗体 modal: 'true',  buttonAlign:"center", bodyStyle:"padding:10px 0 0 15px", /* listeners:{     "show":function() {         //当window show事件发生时清空一下表单         //this.fp.getForm().loadRecord(row);     } },*/            items: [this.fp],            buttons: [{                text: "保存",                handler: this.onSave,                scope: this            }, {                text: "清空",                handler: this.reset,                scope: this            }, {                text: "关闭",                handler: this.closeWin,                scope: this            }]        });        return win;    },        //显示(新增/修改)窗口    showWin: function(status){ //createForm()需要在继承时提供,该方法作用是创建表单        if (!this.win) {            if (!this.fp) {                this.fp = this.createForm();            }            this.win = this.createWin(status);            this.win.on("close", function(){                this.win = null;                this.fp = null;                this.store.reload();            }, this);        }        //窗口关闭时,数据重新加载        this.win.show();    },    //创建(新增/修改)窗口    create: function(){        this.showWin("Save");        this.reset();    },        //数据保存[(新增/修改)窗口]    onSave: function(){        var id = this.fp.form.findField("Id").getValue();        // if(EditTeacherInfofp.getForm().isValid())        this.fp.form.submit({            waitMsg: '正在保存。。。',            url: this.baseUrl + "?cmd=" + (id ? "Update" : "Save"),            method: 'POST',            success: function(){                this.closeWin();                this.store.reload();            },            failure:function(form,action) {                Ext.MessageBox.alert("提示!","信息操作失败!");            },            scope: this        });    },    //(新增/修改)窗口上的清空    reset: function(){        if (this.win)             this.fp.form.reset();    },    //(新增/修改)窗口上的关闭    closeWin: function(){        if (this.win)             this.win.close();        this.win = null;        this.fp = null;        this.store.reload();    },    //修改,双击行,或选中一行点击修改,    onEdit: function(){        if (this.gridPanel.selModel.hasSelection()) {            var records = this.gridPanel.selModel.getSelections();//得到被选择的行的数组            var recordsLen = records.length;//得到行数组的长度            if (recordsLen > 1) {                Ext.Msg.alert("系统提示信息", "请选择其中一项进行编辑!");            }//一次只给编辑一行            else {                var record = this.gridPanel.getSelectionModel().getSelected();//获取选择的记录集                //var id = record.get("id");                this.showWin("Update");                this.fp.form.loadRecord(record); //往表单(fp.form)加载数据            }        }        else {            Ext.Msg.alert("提示", "请先选择要编辑的行!");        }    },    //删除,deleteIds为主键值    onRemove: function(){        var store = this.store;        var baseUrl = this.baseUrl;        if (this.gridPanel.selModel.hasSelection()) {            var records = this.gridPanel.selModel.getSelections();//得到被选择的行的数组            var recordsLen = records.length;//得到行数组的长度            var deleteIds = "";            for (var i = 0; i < recordsLen; i++) {                var id = records[i].get(this.ID);                if (i != 0) {                    deleteIds += "," + id;                }                else {                    deleteIds = id;                }            }                        //this.store.reload();这里能执行            Ext.MessageBox.confirm('系统提示信息', '确定要删除所选的记录吗?', function(btn){                if (btn == 'yes') {                    var myCon = new Ext.data.Connection();                    Ext.MessageBox.wait('正在删除数据中, 请稍候……'); //出现一个等待条                    myCon.request({                        url: baseUrl + '?cmd=Remove',                        method: "POST",                        params: {                            'deleteIds': deleteIds                        },                        //callback : Function (Optional) options, success : Boolean ,response : Object                         callback: function(options, success, response){                            Ext.MessageBox.hide();                            if (success) {                                Ext.Msg.alert("提示信息", "成功删除数据!", function(){                                    store.reload();                                }, this);                            }                            else {                                Ext.MessageBox.alert("系统提示信息", "异步通讯失败,更新失败,请与管理员联系!");                            }                        }                    }, this);                }//if..yes            }, this);        }        else {            Ext.Msg.alert("提示", "请先选择要删除的行!");        }    }});

使用方式:

TeacherInfoPanel = Ext.extend(Ext.darkness.CrudPanel, {    id: "TeacherInfoPanelId",    title: "教师信息管理",    //width: 400,	//height: 300,    //这个是数据源url    baseUrl: "Data/BaseInfo/TeacherInfo.aspx",    storeMapping: ["teacherID","teacherName","teacherSex","postName","PID","teacherPassword","Id"],	ID: "Id",        createForm: function(){        var formPanel = new Ext.form.FormPanel({			plain:true,			layout:"form",			defaultType:"textfield",			labelWidth:75,            baseCls:"x-plain",			//锚点布局-			defaults:{anchor:"95%",msgTarget:"side"},			buttonAlign:"center",			bodyStyle:"padding:0 0 0 0",			items:[{			        name:"teacherID",					fieldLabel:"
教师编号", readOnly:false },{         name:"teacherName", fieldLabel:"
教师姓名", allowBlank:false,                    blankText:"教师姓名不允许为空",                    regex:/^[\s\S]{1,10}$/,                    regexText:"教师姓名请不要超过10个字符" },{                 name:"teacherSex", xtype:"combo", fieldLabel:"教师性别", //传入后台真实值value field /value hiddenName:"teacherSex", readOnly:true, mode:"local", displayField:"show", valueField:"value", triggerAction:"all", value:"男", store:new Ext.data.SimpleStore({ fields:["show","value"], data:[["男","男"],["女","女"]] }) },{         name:"postName", fieldLabel:"
职称", allowBlank:false,                    blankText:"职称不允许为空",                    regex:/^[\s\S]{1,10}$/,                    regexText:"职称请不要超过10个字符" },{         name:"PID", fieldLabel:"身份证号", allowBlank:false,                    blankText:"身份证号不允许为空", regex:/^[0-9.]{15,18}$/,                    regexText:"身份证号为15-18位数字组成" },{            name:"teacherPassword", fieldLabel:"密码", allowBlank:false,                    blankText:"密码不允许为空", regex:/^[0-9.]{6,13}$/,                    regexText:"密码为6-13位数字组成" },{         name: "Id",         xtype: "hidden" }]     });         return formPanel;    },    createWin: function(status){        return this.initWin(380, 300, status);    },     constructor: function(){                this.sm = new Ext.grid.CheckboxSelectionModel();                this.cm = new Ext.grid.ColumnModel([            new Ext.grid.RowNumberer(),//获得行号     this.sm,{         header:"教师编号",         dataIndex:"teacherID",         tooltip:"教师唯一标识",         //可以进行排序                sortable:true         },{         header:"教师姓名",         tooltip:"教师姓名",         dataIndex:"teacherName",                sortable:true,                renderer:function(value)                {                    return "
"+value+"";                }         },{         header:"性别",         width:80,         tooltip:"性别",         dataIndex:"teacherSex",                sortable:true         },{         header:"职称",         width:220,         tooltip:"职称",         dataIndex:"postName",         //可以进行排序                sortable:true         },{         header:"身份证号",         tooltip:"教师身份证号",         width:130,         dataIndex:"PID",                sortable:true,                renderer:function(value)                {                    return "
"+value+"";                }         },{         header:"密码",         width:220,         tooltip:"密码",         dataIndex:"teacherPassword",         //可以进行排序                sortable:true         },{     dataIndex: "Id" }     ]);             TeacherInfoPanel.superclass.constructor.call(this);            }});

使用是,new TeacherInfoPanel()就可以了,实现这样的效果只需144行代码,怎么样!
看一下效果:

  172537_STqu_113740.jpg

转载于:https://my.oschina.net/darkness/blog/510273

你可能感兴趣的文章
Javascript的转义Escape
查看>>
C++结构体中的静态变量
查看>>
JSON.parse()和JSON.stringify()
查看>>
mysql 查排名
查看>>
中国最大的融资平台
查看>>
OO第二单元作业小结
查看>>
[华为机试练习题]37.合唱队
查看>>
犯错了~
查看>>
[PHP] 最简单的权限控制设计
查看>>
在虚拟机和主机之间共享文件夹
查看>>
用户场景描述
查看>>
JSAP107
查看>>
cocos2d-x学习笔记12:如何将win32移植到iOS
查看>>
你们可能都小看了Windows!
查看>>
linux下mrtg,cacti,nagios,ganglia的搭建和win/linux主机等的监控。
查看>>
写在网管员世界杂志更名之际
查看>>
用开源工具Xplico助力网络应用层数据解码
查看>>
如何优化cocos2d程序的内存使用和程序大小
查看>>
夏普美人尖AQUOS S2争议中圈粉,美人尖手机魅力何在?
查看>>
比较数据泵和exp/imp对相同数据导出/导入的性能差异
查看>>