1. 程式人生 > 其它 >easyUI edatagrid編輯表格資料

easyUI edatagrid編輯表格資料

技術標籤:JavaScriptjavascriptjseasyui

功能概述

效果圖如下,使用easyUI的datagrid,點選行編輯該行資料,並在完成編輯時將資料上傳到後端介面。
在這裡插入圖片描述

前端程式碼

html

<table id="dataGrid" title="" class="easyui-datagrid" singleSelect="true"
               pagination="true"
               rownumbers="
true"
fitColumns="true" pageSize=20 url="../dataGrid" data-options=" iconCls: 'icon-edit', onClickCell: onClickCell, ">
<thead> <tr> <
th
data-options="field:'material_name',width:100,sortable:true">
物資名稱</th> <th data-options="field:'unit_name',width:100,sortable:true">計量單位</th> <th data-options="field:'amount',width:100,sortable:true,editor:{type:'numberbox'}"
>
採購數量</th> <th data-options="field:'unit_price',width:100,sortable:true,editor:{type:'numberbox',options:{precision:2}}">單價</th> <th data-options="field:'total_price',width:100,sortable:true">總價</th> <th data-options="field:'pre_arrival_date_str',width:100,sortable:true,editor:'datebox'">預計到貨日期</th> <th data-options="field:'purchase_status',width:100,sortable:true,formatter:formatPurchaseStatus,editor:{type:'checkbox',options:{on:'2',off:'1'}}">是否完全採購</th> <th data-options="field:'remarks',width:100,sortable:true,editor:'text'">備註</th> </tr> </thead> </table>

editor 屬性值型別string,object。 指明編輯型別。當字串指明編輯型別的時候,物件包含2個屬性:type和options
type:字串,該編輯型別可以使用的型別有:text,textarea,checkbox,numberbox,validatebox,datebox,combobox,combotree。
options:物件,object, 該編輯器屬性對應於編輯型別。

js

<script type="text/javascript" src="../jquery.edatagrid.js" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
        initEditDataGrid();
    });

    function initEditDataGrid(){
        $('#dataGrid').edatagrid({
            onDblClickRow:function(){		//雙擊行時觸發 結束編輯
                endEditing();
            },
            onSave:function (index,row) {	//當行上的編輯操作完成時觸發 儲存改動的資料
                var rows = $('#dataGrid').datagrid('getChanges');
                if(rows.length>0){
                    saveInfoList();
                }
            }
        });
    }

    var editIndex = undefined;		//當前正在編輯的行索引值
    /**關閉正在編輯行的編輯狀態*/ 
    function endEditing(){			
        if (editIndex == undefined){return true}
        if ($('#dataGrid').datagrid('validateRow', editIndex)){		
            $('#dataGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }

	/**單擊單元格時 開啟當前行編輯狀態 關閉其他行編輯狀態*/
    function onClickCell(index, field){	
        if (editIndex != index){
            if (endEditing()){
                $('#dataGrid').datagrid('selectRow', index)
                    .datagrid('beginEdit', index);
                var ed = $('#dataGrid').datagrid('getEditor', {index:index,field:field});
                if (ed){
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
                editIndex = index;
            } else {
                setTimeout(function(){
                    $('#dataGrid').datagrid('selectRow', editIndex);
                },0);
            }
        }
    }

	/**提交所有從載入或者上一次呼叫acceptChanges函式後更改的資料。
		通俗的講就是呼叫之後,改變了的資料狀態變為未改變
		如果先執行accept()緊接著執行getChanges()獲取到的資料rows就會為[]*/
    function accept(){
        if (endEditing()){
            var rows = $('#dataGrid').datagrid('acceptChanges');
        }
    }
   	/**獲取改變的行*/
    function getChanges(){
        var rows = $('#dataGrid').datagrid('getChanges');
        alert(rows.length+' rows are changed!');
    }

	function saveInfoList() {
        var rows = $('#dataGrid').datagrid('getChanges');
        var data = {
            'id':order_id
        };
        if(rows.length > 0){
            data.info_list = rows;
        }
        var dataJson = JSON.stringify(data)
        console.log(data);
        $.ajax({
            url: '/updateOrderBatch',		//自己的後端介面地址
            type: 'POST',
            data:dataJson,
            dataType: 'json',				
            contentType:'application/json',
            success: function(result){
                if(result.success){			//修改成功執行自己的業務邏輯
                    accept();				//提交更改的資料,也就是另資料都變為未改變的狀態
                    alert('修改成功')
                }else{
                    alert('修改異常')
                }
            }
        });
    }
</script>

後端介面程式碼

/**controller*/
    @RequestMapping("/updateOrderBatch")
    @ResponseBody
    public Json updateOrderBatch(@RequestBody PurchaseOrderDTO dto) throws Throwable{
        Json json = new Json();
        boolean flag = false;
        try{
            service.updateOrderBatch(dto);
            flag = true;
        }catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(flag);
            json.setMsg(e.getMessage());
            return json;
        }
        json.setSuccess(flag);
        json.setMsg(flag ? "修改成功" : "修改失敗");
        return json;
    }

/**service*/
    @Transactional
    public void updateOrderBatch(PurchaseOrderDTO dto) throws Exception{
        PurchaseOrderDO record = this.getById(dto.getId());
        if (null == record){
            throw new FailedException("未找到相關記錄");
        }
      
        List<PurchaseOrderinfoDTO> infoList = dto.getInfoList();
        if(null!=infoList && infoList.size()>0){
            for(PurchaseOrderinfoDTO info : infoList){
                orderinfoService.updateOrderinfo(info);		//updateOrderinfo()是修改一條資料的方法,需根據自己業務邏輯,此處省略
            }
        }
    }


@Data
public class PurchaseOrderDTO {
	private Integer id;
    private List<PurchaseOrderinfoDTO> infoList;
}