2、easyUI-创建 CRUD可编辑dataGrid(表格)

在介绍这节之前,我们先看一下效果图:

双击可以进入编辑

点击添加可以在下一行显示

应用场景,一般不用于这种用户添加(此处只是示例),一般用于多记录,如学历信息,工作经历等

在这之前,我们要在index.php中引入jquery.edatagrid.js文件,可以去网站下载,稍后也会附出文件以代码的形式;

在前一节中,我们需要修改的有两个地方(优化后的代码基础上),第一index.php页面,第二稍稍增加或者改动userAction和userModel文件;

首先附上index.php代码,然后解释以下:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>dataGrid</title>
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/color.css">
    <script src="../ui/jquery-easyui-1.4.5/jquery.min.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/jquery.easyui.min.js"></script>
    <script src="../js/crud/jquery.edatagrid.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/locale/easyui-lang-zh_CN.js"></script>
    <!--<script src="../js/crud/bus_pubuser.js"></script>-->
    <script>
    $(function(){
        $('#dg').edatagrid({
            url: './data/crud/userAction.php?flag=list',
            saveUrl: './data/crud/userAction.php?flag=add',
            updateUrl: './data/crud/userAction.php?flag=modify',
            destroyUrl: './data/crud/userAction.php?flag=delete'
        });
    });
    </script>
</head>
<body>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:list
    -->
    <table id="dg" title="用户列表" class="easyui-datagrid"  style="width:550px;height:250px"  toolbar="#toolbar" idField="id" rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="fname" width="50" editor="{type:'validatebox',options:{required:true}}">名</th>
                <th field="lname" width="50" editor="{type:'validatebox',options:{required:true}}">姓</th>
                <th field="sex" width="50" editor="{type:'validatebox',options:{required:true}}">性别</th>
                <th field="phone" width="50" editor="{type:'validatebox',options:{required:true}}">联系电话</th>
                <th field="email" width="50" editor="{type:'validatebox',options:{required:true}}">邮件</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:$('#dg').edatagrid('addRow')">添加</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="javascript:$('#dg').edatagrid('destroyRow')">删除</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:$('#dg').edatagrid('saveRow')">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-undo" plain="true" onclick="javascript:$('#dg').edatagrid('cancelRow')">取消</a>
    </div>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:dialog
    -->
    <!--<div id="dlg" class="easyui-dialog" style="width:400px;height:320px;padding:10px 20px;" closed="true" modal="true" buttons="#dlg-buttons">
        <div class="ftitle">基本信息</div>
        <hr />
        <form id="fm" method="post">
            <div class="fitem">
                <p>
                    <label>First Name:</label>
                    <input name="fname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Last Name:</label>
                    <input name="lname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Sex:</label>
                    <input name="sex" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Phone:</label>
                    <input name="phone">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Email:</label>
                    <input name="email" class="easyui-validatebox" validType="email">
                </p>
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
    </div>-->
</body>
<html>

页面中table属性要更改,加入属性idField="id" 去除url属性,idField表示指明哪一个字段是标识字段。其中form表单可以去掉不需要弹出形式了;

/***********************/

在table的列中添加如下代码:editor="{type:'validatebox',options:{required:true}}",

editor属性指明编辑类型。当字符串指明编辑类型的时候,对象包含2个属性:
type:字符串,该编辑类型可以使用的类型有:text,textarea,checkbox,numberbox,validatebox,datebox,combobox,combotree。
options:对象,object, 该编辑器属性对应于编辑类型。

/***********************/

在head头部中可以看到,添加了如下代码:

<script>
    $(function(){
        $('#dg').edatagrid({
            url: './data/crud/userAction.php?flag=list',
            saveUrl: './data/crud/userAction.php?flag=add',
            updateUrl: './data/crud/userAction.php?flag=modify',
            destroyUrl: './data/crud/userAction.php?flag=delete'
        });
    });
</script>

指定url表示获取用户列表信息list

saveUrl表示新增用户保存动作(支持批量保存)

updateUrl表示更新保存用户动作

destroyUrl表示删除用户动作

在toolbar的按钮变成了onclick="javascript:$('#dg').edatagrid('addRow')"等,这些addRow,destroyRow等你可以去js中看或者修改,不然就记住直接使用;

 

准备好之后,还是启用原来的后台代码,list,delete,update,都没用问题,但是add出现了错误,

跟踪代码知道,在add新增的时候,提交post表单的时候有一个新的属性isNewRecord等于true的也被提交过去了(ps,如果在之前的代码中,如果我使用每一个字段都去匹配的话,就不会出现这个问题,但是考虑到如果有很多的字段,你每个都去匹配的话,将会很耽误时间,所以就直接使用$_POST当做数组直接过去了),所以我们需要变更代码;

有两种解决方法,一是,我们直接重新加个flag,比如把saveUrl改成这样, saveUrl: './data/crud/userAction.php?flag=add_special',add_special作为一个新的flag传到后台,如后台userAction.php在switch下条件添加case "add_special" : $user->add_special($_POST);  break; 然后在userModel.php新增add_special方法;

方法如下:

function add_special($arr){
            $medoo = new medoo();
            $fname = $arr["fname"]==null?"":$arr["fname"];
            $lname = $arr["lname"]==null?"":$arr["lname"];
            $sex = $arr["sex"]==null?"":$arr["sex"];
            $phone = $arr["phone"]==null?"":$arr["phone"];
            $email = $arr["email"]==null?"":$arr["email"];
            $sql = $sql = "insert into eui_user(fname,lname,sex,phone,email) values('$fname','$lname','$sex','$phone','$email')";
            $result = $medoo->query($sql);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }

我这里直接每个赋值获取,由于字段比较少的原因(如果字段比较多,大家可以想想其他方法,$_POST提交过来的第一个是isNewRecord,思路是可以去除第一个);

还有一种方法就是,把这个方法直接写在save_user方法下,如下:

function save_user($arr){
            $medoo = new medoo();
            //var_dump($arr);
            if(isset($arr['isNewRecord'])){//可编辑列表
                $fname = $arr["fname"]==null?"":$arr["fname"];
                $lname = $arr["lname"]==null?"":$arr["lname"];
                $sex = $arr["sex"]==null?"":$arr["sex"];
                $phone = $arr["phone"]==null?"":$arr["phone"];
                $email = $arr["email"]==null?"":$arr["email"];
                $sql = $sql = "insert into eui_user(fname,lname,sex,phone,email) values('$fname','$lname','$sex','$phone','$email')";
                $result = $medoo->query($sql);
                if($result){
                    echo json_encode(array('success'=>true));
                }else{
                    echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
                }
            }else{
                $result = $medoo->insert("eui_user",$arr);
                if($result){
                    echo json_encode(array('success'=>true));
                }else{
                    echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
                }
            }
        }
        

这节就完成了,这节代码。其中medoo.php附加了(看上一节)。

所需代码文件(index.php,medoo.php,jquery.edatagrid.js,userAction.php,userModel.php)bus_pubuser.js可以去掉;

index.php

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>dataGrid</title>
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/color.css">
    <script src="../ui/jquery-easyui-1.4.5/jquery.min.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/jquery.easyui.min.js"></script>
    <script src="../js/crud/jquery.edatagrid.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/locale/easyui-lang-zh_CN.js"></script>
    <!--<script src="../js/crud/bus_pubuser.js"></script>-->
    <script>
    $(function(){
        $('#dg').edatagrid({
            url: './data/crud/userAction.php?flag=list',
            saveUrl: './data/crud/userAction.php?flag=add',
            updateUrl: './data/crud/userAction.php?flag=modify',
            destroyUrl: './data/crud/userAction.php?flag=delete'
        });
    });
    </script>
</head>
<body>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:list
    -->
    <table id="dg" title="用户列表" class="easyui-datagrid"  style="width:550px;height:250px"  toolbar="#toolbar" idField="id" rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="fname" width="50" editor="{type:'validatebox',options:{required:true}}">名</th>
                <th field="lname" width="50" editor="{type:'validatebox',options:{required:true}}">姓</th>
                <th field="sex" width="50" editor="{type:'validatebox',options:{required:true}}">性别</th>
                <th field="phone" width="50" editor="{type:'validatebox',options:{required:true}}">联系电话</th>
                <th field="email" width="50" editor="{type:'validatebox',options:{required:true}}">邮件</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:$('#dg').edatagrid('addRow')">添加</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="javascript:$('#dg').edatagrid('destroyRow')">删除</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:$('#dg').edatagrid('saveRow')">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-undo" plain="true" onclick="javascript:$('#dg').edatagrid('cancelRow')">取消</a>
    </div>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:dialog
    -->
    <!--<div id="dlg" class="easyui-dialog" style="width:400px;height:320px;padding:10px 20px;" closed="true" modal="true" buttons="#dlg-buttons">
        <div class="ftitle">基本信息</div>
        <hr />
        <form id="fm" method="post">
            <div class="fitem">
                <p>
                    <label>First Name:</label>
                    <input name="fname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Last Name:</label>
                    <input name="lname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Sex:</label>
                    <input name="sex" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Phone:</label>
                    <input name="phone">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Email:</label>
                    <input name="email" class="easyui-validatebox" validType="email">
                </p>
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
    </div>-->
</body>
<html>
View Code

userAction.php

<?php 
    require_once "../../model/crud/userModel.php";
    $flag = $_GET["flag"];
    if(isset($_GET["id"])){
        $id=$_GET["id"];
    }else if(isset($_POST["id"])){
        $id=$_POST["id"];
    }else{
        $id="";
    }
    $user = new userModel();
    switch($flag){
        case "list" : $user->list_user();
            break;
        case "add" : $user->save_user($_POST);
            break;
        case "modify" : $user->edit_user($_POST,$id);
            break;
        case "delete" : $user->delete_user($id);
            break;
        //特殊方法
        case "add_special" : $user->add_special($_POST);
            break;
        default: $user->showErrorMsg();
    }
View Code

userModel.php

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    class userModel{
        function showErrorMsg(){
            echo json_encode(array('errorMsg'=>'没有相应的操作模块!'));
        }
        
        function list_user(){
            $medoo = new medoo();
            $result = $medoo->select("eui_user","*");
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
        }
        
        
        function save_user($arr){
            $medoo = new medoo();
            //var_dump($arr);
            if(isset($arr['isNewRecord'])){//可编辑列表
                $fname = $arr["fname"]==null?"":$arr["fname"];
                $lname = $arr["lname"]==null?"":$arr["lname"];
                $sex = $arr["sex"]==null?"":$arr["sex"];
                $phone = $arr["phone"]==null?"":$arr["phone"];
                $email = $arr["email"]==null?"":$arr["email"];
                $sql = $sql = "insert into eui_user(fname,lname,sex,phone,email) values('$fname','$lname','$sex','$phone','$email')";
                $result = $medoo->query($sql);
                if($result){
                    echo json_encode(array('success'=>true));
                }else{
                    echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
                }
            }else{
                $result = $medoo->insert("eui_user",$arr);
                if($result){
                    echo json_encode(array('success'=>true));
                }else{
                    echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
                }
            }
        }
        
        function edit_user($arr,$id){
            $medoo = new medoo();
            $result = $medoo->update("eui_user",$arr," where id=".$id);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }
        
        function delete_user($id){
            $medoo = new medoo();
            $result = $medoo->delete("eui_user"," where id=".$id);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }
        
        //特殊方法
        function add_special($arr){
            $medoo = new medoo();
            $fname = $arr["fname"]==null?"":$arr["fname"];
            $lname = $arr["lname"]==null?"":$arr["lname"];
            $sex = $arr["sex"]==null?"":$arr["sex"];
            $phone = $arr["phone"]==null?"":$arr["phone"];
            $email = $arr["email"]==null?"":$arr["email"];
            $sql = $sql = "insert into eui_user(fname,lname,sex,phone,email) values('$fname','$lname','$sex','$phone','$email')";
            $result = $medoo->query($sql);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }
        
        
        
    }
View Code

jquery.edatagrid.js

    /**
     * edatagrid - jQuery EasyUI
     *
     * Licensed under the GPL:
     * http://www.gnu.org/licenses/gpl.txt
     *
     * Copyright 2011-2015 www.jeasyui.com
     *
     * Dependencies:
     * datagrid
     * messager
     *
     */
    (function($){
        // var oldLoadDataMethod = $.fn.datagrid.methods.loadData;
        // $.fn.datagrid.methods.loadData = function(jq, data){
        //     jq.each(function(){
        //         $.data(this, 'datagrid').filterSource = null;
        //     });
        //     return oldLoadDataMethod.call($.fn.datagrid.methods, jq, data);
        // };

        var autoGrids = [];
        function checkAutoGrid(){
            autoGrids = $.grep(autoGrids, function(t){
                return t.length && t.data('edatagrid');
            });
        }
        function saveAutoGrid(omit){
            checkAutoGrid();
            $.map(autoGrids, function(t){
                if (t[0] != $(omit)[0]){
                    t.edatagrid('saveRow');
                }
            });
            checkAutoGrid();
        }
        function addAutoGrid(dg){
            checkAutoGrid();
            for(var i=0; i<autoGrids.length; i++){
                if ($(autoGrids[i])[0] == $(dg)[0]){return;}
            }
            autoGrids.push($(dg));
        }
        function delAutoGrid(dg){
            checkAutoGrid();
            autoGrids = $.grep(autoGrids, function(t){
                return $(t)[0] != $(dg)[0];
            });
        }

        $(function(){
            $(document).unbind('.edatagrid').bind('mousedown.edatagrid', function(e){
                var p = $(e.target).closest('div.datagrid-view,div.combo-panel,div.window,div.window-mask');
                if (p.length){
                    if (p.hasClass('datagrid-view')){
                        saveAutoGrid(p.children('table'));
                    }
                    return;
                }
                saveAutoGrid();
            });
        });
        
        function buildGrid(target){
            var opts = $.data(target, 'edatagrid').options;
            $(target).datagrid($.extend({}, opts, {
                onDblClickCell:function(index,field,value){
                    if (opts.editing){
                        $(this).edatagrid('editRow', index);
                        focusEditor(target, field);
                    }
                    if (opts.onDblClickCell){
                        opts.onDblClickCell.call(target, index, field, value);
                    }
                },
                onClickCell:function(index,field,value){
                    // if (opts.editing && opts.editIndex >= 0){
                    //     $(this).edatagrid('editRow', index);
                    //     focusEditor(target, field);
                    // }
                    if (opts.editIndex >= 0){
                        var dg = $(this);
                        if (opts.editing){
                            dg.edatagrid('editRow', index);
                        } else {
                            setTimeout(function(){
                                dg.edatagrid('selectRow', opts.editIndex);
                            }, 0);
                        }
                        focusEditor(target, field);
                    }
                    if (opts.onClickCell){
                        opts.onClickCell.call(target, index, field, value);
                    }
                },
                onBeforeEdit: function(index, row){
                    if (opts.onBeforeEdit){
                        if (opts.onBeforeEdit.call(target, index, row) == false){
                            return false;
                        }
                    }
                    if (opts.autoSave){
                        addAutoGrid(this);
                    }
                    opts.originalRow = $.extend(true, [], row);
                },
                onAfterEdit: function(index, row){
                    delAutoGrid(this);
                    opts.editIndex = -1;
                    var url = row.isNewRecord ? opts.saveUrl : opts.updateUrl;
                    if (url){
                        var changed = false;
                        var fields = $(this).edatagrid('getColumnFields',true).concat($(this).edatagrid('getColumnFields'));
                        for(var i=0; i<fields.length; i++){
                            var field = fields[i];
                            var col = $(this).edatagrid('getColumnOption', field);
                            if (col.editor && opts.originalRow[field] != row[field]){
                                changed = true;
                                break;
                            }
                        }
                        if (changed){
                            opts.poster.call(target, url, row, function(data){
                                if (data.isError){
                                    var originalRow = opts.originalRow;
                                    $(target).edatagrid('cancelRow',index);
                                    $(target).edatagrid('selectRow',index);
                                    $(target).edatagrid('editRow',index);
                                    opts.originalRow = originalRow;
                                    opts.onError.call(target, index, data);
                                    return;
                                }
                                data.isNewRecord = null;
                                $(target).datagrid('updateRow', {
                                    index: index,
                                    row: data
                                });
                                if (opts.tree){
                                    var idValue = row[opts.idField||'id'];
                                    var t = $(opts.tree);
                                    var node = t.tree('find', idValue);
                                    if (node){
                                        node.text = row[opts.treeTextField];
                                        t.tree('update', node);
                                    } else {
                                        var pnode = t.tree('find', row[opts.treeParentField]);
                                        t.tree('append', {
                                            parent: (pnode ? pnode.target : null),
                                            data: [{id:idValue,text:row[opts.treeTextField]}]
                                        });
                                    }
                                }
                                opts.onSuccess.call(target, index, row);
                                opts.onSave.call(target, index, row);
                            }, function(data){
                                opts.onError.call(target, index, data);
                            });
                        } else {
                            opts.onSave.call(target, index, row);
                        }
                    } else {
                        opts.onSave.call(target, index, row);
                    }
                    if (opts.onAfterEdit) opts.onAfterEdit.call(target, index, row);
                },
                onCancelEdit: function(index, row){
                    delAutoGrid(this);
                    opts.editIndex = -1;
                    if (row.isNewRecord) {
                        $(this).datagrid('deleteRow', index);
                    }
                    if (opts.onCancelEdit) opts.onCancelEdit.call(target, index, row);
                },
                onBeforeLoad: function(param){
                    if (opts.onBeforeLoad.call(target, param) == false){return false}
                    $(this).edatagrid('cancelRow');
                    if (opts.tree){
                        var node = $(opts.tree).tree('getSelected');
                        param[opts.treeParentField] = node ? node.id : undefined;
                    }
                }
            }));
            
            
            
            if (opts.tree){
                $(opts.tree).tree({
                    url: opts.treeUrl,
                    onClick: function(node){
                        $(target).datagrid('load');
                    },
                    onDrop: function(dest,source,point){
                        var targetId = $(this).tree('getNode', dest).id;
                        var data = {
                            id:source.id,
                            targetId:targetId,
                            point:point
                        };
                        opts.poster.call(target, opts.treeDndUrl, data, function(result){
                            $(target).datagrid('load');
                        });
                    }
                });
            }
        }

        function focusEditor(target, field){
            var opts = $(target).edatagrid('options');
            var t;
            var editor = $(target).datagrid('getEditor', {index:opts.editIndex,field:field});
            if (editor){
                t = editor.target;
            } else {
                var editors = $(target).datagrid('getEditors', opts.editIndex);
                if (editors.length){
                    t = editors[0].target;
                }
            }
            if (t){
                if ($(t).hasClass('textbox-f')){
                    $(t).textbox('textbox').focus();
                } else {
                    $(t).focus();                    
                }
            }
        }
        
        $.fn.edatagrid = function(options, param){
            if (typeof options == 'string'){
                var method = $.fn.edatagrid.methods[options];
                if (method){
                    return method(this, param);
                } else {
                    return this.datagrid(options, param);
                }
            }
            
            options = options || {};
            return this.each(function(){
                var state = $.data(this, 'edatagrid');
                if (state){
                    $.extend(state.options, options);
                } else {
                    $.data(this, 'edatagrid', {
                        options: $.extend({}, $.fn.edatagrid.defaults, $.fn.edatagrid.parseOptions(this), options)
                    });
                }
                buildGrid(this);
            });
        };
        
        $.fn.edatagrid.parseOptions = function(target){
            return $.extend({}, $.fn.datagrid.parseOptions(target), {
            });
        };
        
        $.fn.edatagrid.methods = {
            options: function(jq){
                var opts = $.data(jq[0], 'edatagrid').options;
                return opts;
            },
            loadData: function(jq, data){
                return jq.each(function(){
                    $(this).edatagrid('cancelRow');
                    $(this).datagrid('loadData', data);
                });
            },
            enableEditing: function(jq){
                return jq.each(function(){
                    var opts = $.data(this, 'edatagrid').options;
                    opts.editing = true;
                });
            },
            disableEditing: function(jq){
                return jq.each(function(){
                    var opts = $.data(this, 'edatagrid').options;
                    opts.editing = false;
                });
            },
            isEditing: function(jq, index){
                var opts = $.data(jq[0], 'edatagrid').options;
                var tr = opts.finder.getTr(jq[0], index);
                return tr.length && tr.hasClass('datagrid-row-editing');
            },
            editRow: function(jq, index){
                return jq.each(function(){
                    var dg = $(this);
                    var opts = $.data(this, 'edatagrid').options;
                    var editIndex = opts.editIndex;
                    if (editIndex != index){
                        if (dg.datagrid('validateRow', editIndex)){
                            if (editIndex>=0){
                                if (opts.onBeforeSave.call(this, editIndex) == false) {
                                    setTimeout(function(){
                                        dg.datagrid('selectRow', editIndex);
                                    },0);
                                    return;
                                }
                            }
                            dg.datagrid('endEdit', editIndex);
                            dg.datagrid('beginEdit', index);
                            if (!dg.edatagrid('isEditing', index)){
                                return;
                            }
                            opts.editIndex = index;
                            focusEditor(this);
                            
                            var rows = dg.datagrid('getRows');
                            opts.onEdit.call(this, index, rows[index]);
                        } else {
                            setTimeout(function(){
                                dg.datagrid('selectRow', editIndex);
                            }, 0);
                        }
                    }
                });
            },
            addRow: function(jq, index){
                return jq.each(function(){
                    var dg = $(this);
                    var opts = $.data(this, 'edatagrid').options;
                    if (opts.editIndex >= 0){
                        if (!dg.datagrid('validateRow', opts.editIndex)){
                            dg.datagrid('selectRow', opts.editIndex);
                            return;
                        }
                        if (opts.onBeforeSave.call(this, opts.editIndex) == false){
                            setTimeout(function(){
                                dg.datagrid('selectRow', opts.editIndex);
                            },0);
                            return;
                        }
                        dg.datagrid('endEdit', opts.editIndex);
                    }
                    var rows = dg.datagrid('getRows');
                    
                    function _add(index, row){
                        if (index == undefined){
                            dg.datagrid('appendRow', row);
                            opts.editIndex = rows.length - 1;
                        } else {
                            dg.datagrid('insertRow', {index:index,row:row});
                            opts.editIndex = index;
                        }
                    }
                    if (typeof index == 'object'){
                        _add(index.index, $.extend(index.row, {isNewRecord:true}))
                    } else {
                        _add(index, {isNewRecord:true});
                    }
                    
    //                if (index == undefined){
    //                    dg.datagrid('appendRow', {isNewRecord:true});
    //                    opts.editIndex = rows.length - 1;
    //                } else {
    //                    dg.datagrid('insertRow', {
    //                        index: index,
    //                        row: {isNewRecord:true}
    //                    });
    //                    opts.editIndex = index;
    //                }
                    
                    dg.datagrid('beginEdit', opts.editIndex);
                    dg.datagrid('selectRow', opts.editIndex);
                    
                    if (opts.tree){
                        var node = $(opts.tree).tree('getSelected');
                        rows[opts.editIndex][opts.treeParentField] = (node ? node.id : 0);
                    }
                    
                    opts.onAdd.call(this, opts.editIndex, rows[opts.editIndex]);
                });
            },
            saveRow: function(jq){
                return jq.each(function(){
                    var dg = $(this);
                    var opts = $.data(this, 'edatagrid').options;
                    if (opts.editIndex >= 0){
                        if (opts.onBeforeSave.call(this, opts.editIndex) == false) {
                            setTimeout(function(){
                                dg.datagrid('selectRow', opts.editIndex);
                            },0);
                            return;
                        }
                        $(this).datagrid('endEdit', opts.editIndex);
                    }
                });
            },
            cancelRow: function(jq){
                return jq.each(function(){
                    var opts = $.data(this, 'edatagrid').options;
                    if (opts.editIndex >= 0){
                        $(this).datagrid('cancelEdit', opts.editIndex);
                    }
                });
            },
            destroyRow: function(jq, index){
                return jq.each(function(){
                    var dg = $(this);
                    var opts = $.data(this, 'edatagrid').options;
                    
                    var rows = [];
                    if (index == undefined){
                        rows = dg.datagrid('getSelections');
                    } else {
                        var rowIndexes = $.isArray(index) ? index : [index];
                        for(var i=0; i<rowIndexes.length; i++){
                            var row = opts.finder.getRow(this, rowIndexes[i]);
                            if (row){
                                rows.push(row);
                            }
                        }
                    }
                    
                    if (!rows.length){
                        $.messager.show({
                            title: opts.destroyMsg.norecord.title,
                            msg: opts.destroyMsg.norecord.msg
                        });
                        return;
                    }
                    
                    $.messager.confirm(opts.destroyMsg.confirm.title,opts.destroyMsg.confirm.msg,function(r){
                        if (r){
                            for(var i=0; i<rows.length; i++){
                                _del(rows[i]);
                            }
                            dg.datagrid('clearSelections');
                        }
                    });
                    
                    function _del(row){
                        var index = dg.datagrid('getRowIndex', row);
                        if (index == -1){return}
                        if (row.isNewRecord){
                            dg.datagrid('cancelEdit', index);
                        } else {
                            if (opts.destroyUrl){
                                var idValue = row[opts.idField||'id'];
                                opts.poster.call(dg[0], opts.destroyUrl, {id:idValue}, function(data){
                                    var index = dg.datagrid('getRowIndex', idValue);
                                    if (data.isError){
                                        dg.datagrid('selectRow', index);
                                        opts.onError.call(dg[0], index, data);
                                        return;
                                    }
                                    if (opts.tree){
                                        dg.datagrid('reload');
                                        var t = $(opts.tree);
                                        var node = t.tree('find', idValue);
                                        if (node){
                                            t.tree('remove', node.target);
                                        }
                                    } else {
                                        dg.datagrid('cancelEdit', index);
                                        dg.datagrid('deleteRow', index);
                                    }
                                    opts.onDestroy.call(dg[0], index, row);
                                    var pager = dg.datagrid('getPager');
                                    if (pager.length && !dg.datagrid('getRows').length){
                                        dg.datagrid('options').pageNumber = pager.pagination('options').pageNumber;
                                        dg.datagrid('reload');
                                    }
                                }, function(data){
                                    opts.onError.call(dg[0], index, data);
                                });
                            } else {
                                dg.datagrid('cancelEdit', index);
                                dg.datagrid('deleteRow', index);
                                opts.onDestroy.call(dg[0], index, row);
                            }
                        }
                    }
                });
            }
        };
        
        $.fn.edatagrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
            singleSelect: true,
            editing: true,
            editIndex: -1,
            destroyMsg:{
                norecord:{
                    title:'Warning',
                    msg:'No record is selected.'
                },
                confirm:{
                    title:'Confirm',
                    msg:'你确定要删除么?'
                }
            },
            poster: function(url, data, success, error){
                $.ajax({
                    type: 'post',
                    url: url,
                    data: data,
                    dataType: 'json',
                    success: function(data){
                        success(data);
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        error({
                            jqXHR: jqXHR,
                            textStatus: textStatus,
                            errorThrown: errorThrown
                        });
                    }
                });
            },
            
            autoSave: false,    // auto save the editing row when click out of datagrid
            url: null,    // return the datagrid data
            saveUrl: null,    // return the added row
            updateUrl: null,    // return the updated row
            destroyUrl: null,    // return {success:true}
            
            tree: null,        // the tree selector
            treeUrl: null,    // return tree data
            treeDndUrl: null,    // to process the drag and drop operation, return {success:true}
            treeTextField: 'name',
            treeParentField: 'parentId',
            
            onAdd: function(index, row){},
            onEdit: function(index, row){},
            onBeforeSave: function(index){},
            onSave: function(index, row){},
            onSuccess: function(index, row){},
            onDestroy: function(index, row){},
            onError: function(index, row){}
        });
        
        ////////////////////////////////
        $.parser.plugins.push('edatagrid');
    })(jQuery);
View Code

 

posted on 2016-07-10 14:34  EthanCoco  阅读(4293)  评论(2编辑  收藏  举报

导航