Ext.js5的表格插件—checkbox/编辑等常见需求(15)

本文详细介绍了如何在表格中添加复选框选择功能,并提供了复选框选择的使用方法。同时,还展示了如何实现表格的列编辑功能,包括添加编辑插件和指定编辑列的方法。

view

Ext.define('KitchenSink.view.grid.CheckboxSelection', {
    extend: 'Ext.grid.Panel',

    xtype: 'checkbox-selection',
    store: 'Companies',
    //下文会详细介绍,此处是checkbox的关键
    //官方的例子中只有一个selType,没有selModel,暂时有点没看明白20151218
    //所使用到的选择模型的xtype。默认为'rowmodel'。 如果只是一个配置对象或者在selModel配置中未给出任何指定则在这里将被用来创建选择模型。
    selType: 'checkboxmodel',
    columns: [
        {text: "Company", width: 300, dataIndex: 'name'},
        {text: "Price", formatter: 'usMoney', dataIndex: 'price'},
        {text: "Change", dataIndex: 'change'},
        {text: "% Change", dataIndex: 'pctChange'},
        {text: "Last Updated", width: 120, formatter: 'date("m/d/Y")', dataIndex: 'lastChange'}
    ],
    columnLines: true,
    height: 300,
    frame: true,
    title: 'Framed with Checkbox Selection and Horizontal Scrolling',
    iconCls: 'icon-grid',

    initComponent: function() {
        this.width = 750;
        this.callParent();
    }
});

store

Ext.define('KitchenSink.store.Companies', {
    extend: 'Ext.data.ArrayStore',
    alias: 'store.companies',
    model: 'KitchenSink.model.Company',
    data: [
        [0,  '3m Co',                                       71.72, 0.02,  0.03,  '9/1 12:00am', 'Manufacturing'],
        [1,  'Alcoa Inc',                                   29.01, 0.42,  1.47,  '9/1 12:00am', 'Manufacturing'],
        [2,  'Altria Group Inc',                            83.81, 0.28,  0.34,  '9/1 12:00am', 'Manufacturing'],
        [3,  'American Express Company',                    52.55, 0.01,  0.02,  '9/1 12:00am', 'Finance'],
        [4,  'American International Group, Inc.',          64.13, 0.31,  0.49,  '9/1 12:00am', 'Services'],
        [5,  'AT&T Inc.',                                   31.61, -0.48, -1.54, '9/1 12:00am', 'Services'],
        [6,  'Boeing Co.',                                  75.43, 0.53,  0.71,  '9/1 12:00am', 'Manufacturing'],
        [7,  'Caterpillar Inc.',                            67.27, 0.92,  1.39,  '9/1 12:00am', 'Services'],
        [8,  'Citigroup, Inc.',                             49.37, 0.02,  0.04,  '9/1 12:00am', 'Finance'],
        [9,  'E.I. du Pont de Nemours and Company',         40.48, 0.51,  1.28,  '9/1 12:00am', 'Manufacturing'],
        [10, 'Exxon Mobil Corp',                            68.1,  -0.43, -0.64, '9/1 12:00am', 'Manufacturing'],
        [11, 'General Electric Company',                    34.14, -0.08, -0.23, '9/1 12:00am', 'Manufacturing'],
        [12, 'General Motors Corporation',                  30.27, 1.09,  3.74,  '9/1 12:00am', 'Automotive'],
        [13, 'Hewlett-Packard Co.',                         36.53, -0.03, -0.08, '9/1 12:00am', 'Computer'],
        [14, 'Honeywell Intl Inc',                          38.77, 0.05,  0.13,  '9/1 12:00am', 'Manufacturing'],
        [15, 'Intel Corporation',                           19.88, 0.31,  1.58,  '9/1 12:00am', 'Computer'],
        [16, 'International Business Machines',             81.41, 0.44,  0.54,  '9/1 12:00am', 'Computer'],
        [17, 'Johnson & Johnson',                           64.72, 0.06,  0.09,  '9/1 12:00am', 'Medical'],
        [18, 'JP Morgan & Chase & Co',                      45.73, 0.07,  0.15,  '9/1 12:00am', 'Finance'],
        [19, 'McDonald\'s Corporation',                     36.76, 0.86,  2.40,  '9/1 12:00am', 'Food'],
        [20, 'Merck & Co., Inc.',                           40.96, 0.41,  1.01,  '9/1 12:00am', 'Medical'],
        [21, 'Microsoft Corporation',                       25.84, 0.14,  0.54,  '9/1 12:00am', 'Computer'],
        [22, 'Pfizer Inc',                                  27.96, 0.4,   1.45,  '9/1 12:00am', 'Medical'],
        [23, 'The Coca-Cola Company',                       45.07, 0.26,  0.58,  '9/1 12:00am', 'Food'],
        [24, 'The Home Depot, Inc.',                        34.64, 0.35,  1.02,  '9/1 12:00am', 'Retail'],
        [25, 'The Procter & Gamble Company',                61.91, 0.01,  0.02,  '9/1 12:00am', 'Manufacturing'],
        [26, 'United Technologies Corporation',             63.26, 0.55,  0.88,  '9/1 12:00am', 'Computer'],
        [27, 'Verizon Communications',                      35.57, 0.39,  1.11,  '9/1 12:00am', 'Services'],
        [28, 'Wal-Mart Stores, Inc.',                       45.45, 0.73,  1.63,  '9/1 12:00am', 'Retail'],
        [29, 'Walt Disney Company (The) (Holding Company)', 29.89, 0.24,  0.81,  '9/1 12:00am', 'Services']
    ]
}, function(cls) {
    var data = cls.prototype.config.data;

    for(var i = 0; i < data.length; i++){
        data[i].push('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. ');
    }
});

model

Ext.define('KitchenSink.model.Company', {
    extend: 'KitchenSink.model.Base',
    fields: [
        {name: 'name'},
        {name: 'price', type: 'float'},
        {name: 'change', type: 'float'},
        {name: 'pctChange', type: 'float'},
        {name: 'lastChange', type: 'date',  dateFormat: 'n/j h:ia'},
        {name: 'industry'},
        {name: 'desc'},
        // Trend begins with the cerrent price. Changes get pushed onto the end
        {
            name: 'trend',
            convert: function(value, record) {
                // Record creation call with no trend there: start with current price
                if (value === null) {
                    return [record.get('price')];
                }
                return Ext.isArray(value) ? value : [ value ];
            } 
        },
        // Rating dependent upon performance 0 = best, 2 = worst
        {
            name: 'rating',
            type: 'int',
            convert: function(value, record) {
                var pct = record.get('pctChange');
                if (pct < 0)
                    return 2;
                if (pct < 1)
                    return 1;
                return 0;
            }
        }
    ],

    // Override to keep the last 10 prices in the trend field
    set: function(fieldName, value) {
        if (fieldName === 'price') {
            this.callParent([{
                price: value,
                trend: this.addToTrend(fieldName.price)
            }]);
        }
        else {
            if (typeof fieldName !== 'string' && 'price' in fieldName) {
                fieldName.trend = this.addToTrend(fieldName.price);
            }
            this.callParent(arguments);
        }
    },

    // Override to keep the last 10 prices in the trend field
    addToTrend: function(value) {
        var trend = this.data.trend.concat(value);

        if (trend.length > 10) {
            Ext.Array.splice(trend, 0, trend.length - 10);
        }
        return trend;
    }
});

以下知识来源于齐飞的总结
地址:http://www.cnblogs.com/youring2/p/3998761.html
GridPanel的行选择模型(SelectionModel)
一般情况下,表格中是不会出现复选框的,而是进行的点击行选中,默认为多选(“MULTI”)
如何添加复选框

selType: "checkboxmodel",
selModel: {
    injectCheckbox: 0,
    mode: "SIMPLE",     //"SINGLE"/"SIMPLE"/"MULTI"
    checkOnly: true     //只能通过checkbox选择
},

通过代码选择行

//选择行,并保持其他行的选择状态
grid.getSelectionModel().select(records, true);
//选择所有
grid.getSelectionModel().selectAll();
//根据row index选择
grid.getSelectionModel().selectRange(startRow, endRow, true)

获取选中行

var records = grid.getSelectionModel().getSelection();

显示行号,一般情况下是不显示的

columns: [
    { xtype: 
"rownumberer", text: "序号"

, width:40 },
    { text: '姓名', dataIndex: 'name' },
    {
        text: '年龄', dataIndex: 'age', xtype: 'numbercolumn', format: '0',

    },
    { text: '电话', dataIndex: 'phone', editor: "textfield" }
],

实现表格的列编辑
1、添加编辑插件(行编辑是RowEditing)

plugins: [
    Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit: 1
    })
],

2、为需要编辑的列指定编辑

columns: [
    { xtype: "rownumberer", text: "序号", width:40 },
    { text: '姓名', dataIndex: 'name' },
    {
        text: '年龄', dataIndex: 'age', xtype: 'numbercolumn', format: '0',
        editor: {
            xtype: "numberfield",
            decimalPrecision: 0,
            selectOnFocus: true
        }
    },
    { text: '电话', dataIndex: 'phone', editor: "textfield" }

表格再被编辑后会自动出现小红角,如果要去掉小红角

grid.on('edit', function (editor, e) {
    // commit the changes right after editing finished
    e.record.commit();
});

选中单元格的内容,一般情况下单元格的内容是不可以被选中的

viewConfig:{
    stripeRows:true,//在表格中显示斑马线
    enableTextSelection:true //可以复制单元格文字
}

禁止头部菜单,为每个column定义menuDisabled

{header: 'Idno', dataIndex: 'idno', width:150,menuDisabled:true}
init: function () { var param = new HashMap(); param.put('operate', 'getParam'); Rpc({ functionId: 'GZ00002301', async: false, success: function (data) { var result = Ext.decode(data.responseText); if (result.return_code == 'success') { var returnData = result.return_data; var params = returnData.paramMap; approvalparameter_me.allSalarySet = params.salaryTypeList; approvalparameter_me.salaryMainArr = params.approvalParamList; approvalparameter_me.flowableList = params.flowableList approvalparameter_me.org_id = params.org_id console.log(params) } } }, param); var showData = []; var data = approvalparameter_me.salaryMainArr Ext.each(data, function (item, index) { showData.push(item); }); data.push({ operate:true, id: '', name: '', salary_table: '', salary_type: '', appeal_user: '', approval_report: '', approval_flow: '', approval_org: '' }); //grid面板 的Store approvalparameter_me.mianStore = Ext.create('Ext.data.Store', { storeId: 'mainStore', // 增加排序字段 fields: ['operate','id', 'name', 'salary_table','salary_name', 'salary_type', 'appeal_user', 'approval_report', 'approval_flow','approval_flow_name', 'approval_org', 'approval_org_name'], // 自动加载 data: data }); var states = Ext.create('Ext.data.Store', { id: 'flowableStore', fields: ['dataName', 'dataValue'] }); Ext.each(approvalparameter_me.flowableList, function (obj, index) { states.insert(index, [{dataName: obj.dataName, dataValue: obj.dataValue}]); }); //界面的grid面板 var salaryGrid = Ext.create("Ext.grid.Panel", { store: approvalparameter_me.mianStore, itemId: "salaryGrid", id:'approvalParameterPanel', border: false, bodyStyle: "margin-top:1px;", enableColumnResize: true,//改变列宽 enableColumnMove: false,//拖放列 stripeRows: false,//表格是否隔行换色 columnLines: true,//列分割线 selModel: Ext.create("Ext.selection.CheckboxModel", { mode: "multi",//multi,simple,single;默认为多选multi checkOnly: true,//如果值为true,则只用点击checkbox列才能选中此条记录 enableKeyNav: true, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; //去除操作行的分割线 return "<i class='hj-line hj-line-xinzeng' data-qtip='新增' style='font-size: 18px;cursor:pointer;' onclick='approvalparameter_me.addData()'/>"; }else { return '<span class="' + Ext.baseCSSPrefix + 'grid-checkcolumn" role="presentation"></span>' } } }), viewConfig: { markDirty: false // 禁用脏数据标记 }, columns: [//名称 { text: '名称', dataIndex: 'name', sortable: false, hideable: false, align: 'left', width: 180, editor: { xtype: 'textfield', // 这里定义编辑器的类型 allowBlank: false, listeners: { // 监听编辑完成事件 blur: function(field) { var editor = field.up('editor'); // 获取编辑器组件 var record = editor.context.record; // 获取当前编辑的记录 console.log('当前行数据:', record.data); console.log('字段名:', editor.context.column.dataIndex); console.log('行索引:', editor.context.rowIdx); var currentid = record.data.id; var param = new HashMap(); param.put('operate', 'save'); param.put('opt', 'saveName'); param.put("id", currentid); param.put("value", field.value); Rpc({ functionId: 'GZ00002301', async: false, success: function (data) { var result = Ext.decode(data.responseText); if (result.return_code == 'success') { var returnData = result.return_data; //record.data.id开头是ext,更新record.data.id 为params.returnValue if (record.data.id && record.data.id.toString().startsWith('ext')) { // 更新record.data.id为params.returnValue record.set('id', returnData.returnValue); console.log('更新ID:', returnData.returnValue); } } } }, param); } } }, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { var html = value; if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; //去除操作行的分割线 } if (record.data.operate) { html= "<i class='hj-line hj-line-shanchu' data-qtip='删除' style='font-size: 18px;cursor:pointer;' onclick='approvalparameter_me.delData()'/>"; } return html; } },// 薪资类别 { text: '薪资类别', dataIndex: 'salary_name', sortable: false, hideable: false, align: 'left', width: 300, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; // 去除操作行的分割线 } else { if (!value){ value = '' } var html = '<div style="display: flex; justify-content: space-between; align-items: center; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100%;">'; // 使用 flexbox // 在此处添加 data-qtip,给出完整值 html += '<div style="text-align: left; flex-grow: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: 80%;" data-qtip="' + Ext.util.Format.htmlEncode(value) + '">' + value + '</div>'; // value 超出部分显示省略号 html += '<a onclick="approvalparameter_me.createSetSalerySetWin(\''; html += record.data.id; html += '\',\''+rowIndex+'\')"><i class="hj-line hj-line-peizhicanshu" data-qtip="' + gz.label.attribute + '"></i></a>'; html += '</div>'; return html; } } },//报批用户 { text: '报批用户', dataIndex: 'appeal_user', sortable: false, hideable: false, align: 'left', width: 180, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; //去除操作行的分割线 }else { var orgId = record.data.org_id; if (value) { var name = record.data.userfullname; if (record.data.fullname) { name+='(' + record.data.fullname + ')'; } var showName = name; var personImgId='user_name_' + record.data.id; var photoUrl =record.data.photoPath; if (photoUrl == "/images/photo.jpg") { photoUrl = rootPath+ photoUrl; } // var qtipName = recorddata.fullname?record.data.username+ '(' +record.data.fullname + ')':record.data.username; return '<div id="'+ personImgId +'"><div style="margin-top:-10px;position:relative; padding-right:8px;" data-qtip="' + name + '">' + '<img id="'+ personImgId +'_photo" width=30 height=30 onclick="approvalparameter_me.createPersonPicker(\''+ orgId +'\',\''+ rowIndex +'\', \''+ personImgId +'\', \''+ record.data.id +'\')" style="border-radius: 100%;vertical-align:middle;margin:0px 4px 0px 0px;padding-top: 0px;cursor:pointer;" src='+photoUrl+' />'+ '<span style="display:inline-block;margin-top:10px;" id="'+ personImgId +'_name">'+ showName +'</span>'+ '</div></div>'; } else { var personImgId = 'user_name_' + orgId + '_' + rowIndex; var html = '<div id="'+ personImgId +'" style="width:98%;display:flex;">'; html = html + '<i onclick="approvalparameter_me.createPersonPicker(\''+orgId+'\',\''+ rowIndex +'\', \''+ personImgId +'\', \''+ record.data.id +'\')" '; html = html + ' class="hj-workflow hj-workflow-zengjiarenwu" style="font-size: 18px;float:right;margin-right:5px;cursor:pointer;"></i>'; html = html + '<span style="float: right"></span></div>'; return html; } } } },// 审批报表 { text: '审批报表', dataIndex: 'approval_report', sortable: false, hideable: false, align: 'left', width: 100, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; //去除操作行的分割线 }else { var html = '<div style="display: flex; justify-content: center; align-items: center;">'; // 使用 flexbox 并居中 html += '<a onclick="approvalparameter_me.openProperty(\''; html += 'salaryid'; html += '\',\'' + '' + '\',\'' + '' + '\')"><i class="hj-line hj-line-peizhicanshu" data-qtip="' + gz.label.attribute + '"></i></a>'; html += '</div>'; return html; } } },// 审批流程 { text: '审批流程', dataIndex: 'approval_flow_name', sortable: false, hideable: false, align: 'left', width: 200, editor: { xtype: 'combobox', store: states, // 根据需求替换成实际的流程数据 editable: false, forceSelection: true, queryMode: 'local', displayField: 'dataName', valueField: 'dataValue', emptyText: "请选择流程", value: 'xz', listeners: { afterrender: function (combo) { combo.setValue('cs'); // 手动设置值 }, select: function (combo,newValue, oldValue) { var editor = combo.up('editor'); var grid = editor.up('gridpanel'); var rowIndex = editor.context.rowIdx; approvalparameter_me.mianStore.data.items[rowIndex].data.approval_flow = newValue.data.dataValue; approvalparameter_me.mianStore.data.items[rowIndex].data.approval_flow_name = newValue.data.dataName; var record = editor.context.record; var param = new HashMap(); param.put('operate', 'save'); param.put('opt', 'saveaApprovalFlow'); param.put("id", record.id); param.put("value", newValue.data.dataValue); Rpc({ functionId: 'GZ00002301', async: false, success: function (data) { var result = Ext.decode(data.responseText); if (result.return_code == 'success') { Ext.showAlert('保存成功!'); approvalparameter_me.mianStore.load(); } } }, param); } } }, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; //去除操作行的分割线 }else { return value; } } },// 所属组织 { text: '所属组织', dataIndex: 'approval_org_name', sortable: false, hideable: false, align: 'left', width: 220, renderer: function (value, metaData, record, rowIndex, colIndex, store, view) { if (record.data.operate) { metaData.tdStyle = 'border-width:0px !important'; //去除操作行的分割线 }else { if (!value){ value = '' } var salaryid = record.data.salaryid_safe; var html = '&nbsp&nbsp<a href="javascript:;" onclick="approvalparameter_me.openSelectPerson(this,\''+salaryid+'\',\'' + record.data.approval_org + '\',\'' + record.data.id + '\')"><i style="padding-right: 4px;" class="hj-line hj-line-zuzhijigou"></i>'+value+'</a>'; return html; } } } ], plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { // 添加单元格编辑插件 clicksToEdit: 1 // 单击一次进入编辑状态 }) ], listeners: { cellclick: function (grid, td, cellIndex, record, tr, rowIndex, e, options) { // 判断点击的列是否是审批流程列 if (cellIndex === grid.getColumnManager().getHeaderIndex('审批流程')) { // 启动单元格编辑 grid.getPlugin().startEdit(record, cellIndex); } } } }); approvalparameter_me.add(salaryGrid); }最后一行数据的operate为true
最新发布
08-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值