0

我调整了这个链接Local form editing demo and jqGrid 4.4.1以适应我的解决方案,但是我已经更改了CloseAfterAdd:false并添加了ClearAfterAdd:trueand beforeSubmit: CheckValid。但是,这两个事件都没有触发以实现我的目标。我的目标是在使用回车键作为保存键添加记录时保持对话框表单打开,并在保存后清除表单。其次验证 CheckValid 函数中的一组相关字段。请有人指出我做错了什么。谢谢

function checkvalue(value, colname) { alert(value || colname); return [true, ""]; }
        var vlcontractor, field2, field3, field4, vlBuckid, vlHospid, myCustomCheck, myCustomCheck2;
        myCustomCheck = function (value, colname) {
            switch (colname) {
                case 'Contractor':
                    vlcontractor = value;
                    break;
                case 'Company Name':
                    field2 = value;
                    break;
                case 'Project End Date':
                    field3 = value;
                    break;
                default:
                    break;
            }

            if (vlcontractor == "Yes" && (field2 == undefined || field3 == undefined))
            { return [false, "Company/State ID/End Date is needed for a Contractor"]; }

            if (vlcontractor != undefined  && field2 != undefined) {
                // validate the fields here
                return [false, "some error text"];
            } else {
                //alert('we are good');
                return [true];
            }
        };
        myCustomCheck2 = function (value, colname) {
            switch (colname) {
                case 'BUCK ID':
                    vlBuckid = value;
                    break;
                case 'Hospital ID':
                    vlHospid = value;
                    break;
            }
            if ((vlBuckid == undefined && vlHospid == undefined) || (vlBuckid == '' && vlHospid == ''))
            { return [false, "A BuckID or Hospital ID is required."]; }
            else { return [true]; }
        }

        $(function () {
            var lastSel,
            mydata = '',
                grid = $("#list"),
                getColumnIndex = function (columnName) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
                    for (i = 0; i < l; i++) {
                        if ((cm[i].index || cm[i].name) === columnName) {
                            return i; // return the colModel index
                        }
                    }
                    return -1;
                },
                CheckValid = function (postdata, formid) {
                    alert(postdata);
                    return false;
                },
                onclickSubmitLocal = function (options, postdata) {
                    var $this = $(this), grid_p = this.p,
                        idname = grid_p.prmNames.id,
                        grid_id = this.id,
                        id_in_postdata = grid_id + "_id",
                        rowid = postdata[id_in_postdata],
                        addMode = rowid === "_empty",
                        oldValueOfSortColumn,
                        new_id,
                        tr_par_id,
                        colModel = grid_p.colModel,
                        cmName,
                        iCol,
                        cm;

                    // postdata has row id property with another name. we fix it:
                    if (addMode) {
                        // generate new id
                        new_id = $.jgrid.randId();
                        while ($("#" + new_id).length !== 0) {
                            new_id = $.jgrid.randId();
                        }
                        postdata[idname] = String(new_id);
                    } else if (typeof postdata[idname] === "undefined") {
                        // set id property only if the property not exist
                        postdata[idname] = rowid;
                    }
                    delete postdata[id_in_postdata];

                    // prepare postdata for tree grid
                    if (grid_p.treeGrid === true) {
                        if (addMode) {
                            tr_par_id = grid_p.treeGridModel === 'adjacency' ? grid_p.treeReader.parent_id_field : 'parent_id';
                            postdata[tr_par_id] = grid_p.selrow;
                        }

                        $.each(grid_p.treeReader, function (i) {
                            if (postdata.hasOwnProperty(this)) {
                                delete postdata[this];
                            }
                        });
                    }

                    // decode data if there encoded with autoencode
                    if (grid_p.autoencode) {
                        $.each(postdata, function (n, v) {
                            postdata[n] = $.jgrid.htmlDecode(v); // TODO: some columns could be skipped
                        });
                    }

                    // save old value from the sorted column
                    oldValueOfSortColumn = grid_p.sortname === "" ? undefined : grid.jqGrid('getCell', rowid, grid_p.sortname);

                    // save the data in the grid
                    if (grid_p.treeGrid === true) {
                        if (addMode) {
                            $this.jqGrid("addChildNode", new_id, grid_p.selrow, postdata);
                        } else {
                            $this.jqGrid("setTreeRow", rowid, postdata);
                        }
                    } else {
                        if (addMode) {
                            // we need unformat all date fields before calling of addRowData
                            for (cmName in postdata) {
                                if (postdata.hasOwnProperty(cmName)) {
                                    iCol = getColumnIndex.call(this, cmName);
                                    if (iCol >= 0) {
                                        cm = colModel[iCol];
                                        if (cm && cm.formatter === "date") {
                                            postdata[cmName] = $.unformat.date.call(this, postdata[cmName], cm);
                                        }
                                    }
                                }
                            }
                            $this.jqGrid("addRowData", new_id, postdata, options.addedrow);
                        } else {
                            $this.jqGrid("setRowData", rowid, postdata);
                        }
                    }

                    if ((addMode && options.closeAfterAdd) || (!addMode && options.closeAfterEdit)) {
                        // close the edit/add dialog
                        $.jgrid.hideModal("#editmod" + grid_id, {
                            gb: "#gbox_" + grid_id,
                            jqm: options.jqModal,
                            onClose: options.onClose
                        });
                    }

                    if (postdata[grid_p.sortname] !== oldValueOfSortColumn) {
                        // if the data are changed in the column by which are currently sorted
                        // we need resort the grid
                        setTimeout(function () {
                            $this.trigger("reloadGrid", [{ current: true}]);
                        }, 100);
                    }

                    // !!! the most important step: skip ajax request to the server
                    options.processing = true;
                    $('#gridData').val(JSON.stringify(grid_p.data));
                    return {};
                },
                editSettings = {
                    //recreateForm: true,
                    jqModal: false,
                    reloadAfterSubmit: false,
                    closeOnEscape: true,
                    savekey: [true, 13],
                    closeAfterEdit: true,
                    beforeSubmit: CheckValid,
                    onclickSubmit: onclickSubmitLocal
                },
                addSettings = {
                    //recreateForm: true,
                    jqModal: false,
                    beforeSubmit: CheckValid,
                    reloadAfterSubmit: false,
                    savekey: [true, 13],
                    closeOnEscape: true,
                    closeAfterAdd: true,
                    clearAfterAdd: true,
                    onclickSubmit: onclickSubmitLocal
                },
                delSettings = {
                    // because I use "local" data I don't want to send the changes to the server
                    // so I use "processing:true" setting and delete the row manually in onclickSubmit
                    onclickSubmit: function (options, rowid) {
                        var $this = $(this), grid_id = $.jgrid.jqID(this.id), grid_p = this.p,
                            newPage = grid_p.page;

                        // reset the value of processing option to true to
                        // skip the ajax request to 'clientArray'.
                        options.processing = true;

                        // delete the row
                        $this.jqGrid("delRowData", rowid);
                        if (grid_p.treeGrid) {
                            $this.jqGrid("delTreeNode", rowid);
                        } else {
                            $this.jqGrid("delRowData", rowid);
                        }
                        $.jgrid.hideModal("#delmod" + grid_id, {
                            gb: "#gbox_" + grid_id,
                            jqm: options.jqModal,
                            onClose: options.onClose
                        });

                        if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
                            if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
                                // if after deliting there are no rows on the current page
                                // which is the last page of the grid
                                newPage--; // go to the previous page
                            }
                            // reload grid to make the row from the next page visable.
                            $this.trigger("reloadGrid", [{ page: newPage}]);
                        }

                        return true;
                    },
                    processing: true
                },
                initDateEdit = function (elem) {
                    setTimeout(function () {
                        $(elem).datepicker({
                            dateFormat: 'dd-M-yy',
                            //autoSize: true,
                            showOn: 'button',
                            changeYear: true,
                            changeMonth: true,
                            showButtonPanel: true,
                            showWeek: true
                        });
                    }, 100);
                },
                initDateSearch = function (elem) {
                    setTimeout(function () {
                        $(elem).datepicker({
                            dateFormat: 'dd-M-yy',
                            //autoSize: true,
                            //showOn: 'button', // it dosn't work in searching dialog
                            changeYear: true,
                            changeMonth: true,
                            showButtonPanel: true,
                            showWeek: true
                        });
                    }, 100);
                };
            grid.jqGrid({
                datatype: 'local',
                data: mydata,
                //colNames: [/*'Inv No', */'Client', 'Date', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'],
                colNames: ['Emp/Stu ID', 'Last Name, First Name', 'BUCK ID', 'Hospital ID', 'Contractor', 'Company-Name', 'State ID', 'Project End Date'],
                colModel: [
                        { name: 'empstuid', index: 'empstuid', editable: true, width: 80, editrules: { required: false }, editoptions: { maxlength: 10 } },
                        { name: 'lastFirst', index: 'lastFirst', editable: true, width: 180, editrules: { required: true} },
                        { name: 'buckid', index: 'buckid', editable: true, width: 120, editrules: { custom: true, custom_func: myCustomCheck2 } },
                        { name: 'hospid', index: 'hospid', editable: true, width: 120, editrules: { custom: true, custom_func: myCustomCheck2 } },
                        {
                            name: 'contractor', index: 'contractor', editable: true, edittype: 'checkbox',
                            editoptions: { value: "Yes:No" }, width: 70, editrules: { custom: true, custom_func:myCustomCheck }
                        },
                        { name: 'compname', index: 'compname', editable: true, width: 110, editrules: { custom: true, custom_func:myCustomCheck } },
                        { name: 'stateid', index: 'stateid', editable: true, width: 80, editrules: { custom: true, custom_func: myCustomCheck } },
                        { name: 'enddate', index: 'enddate', editable: true, width: 110, editrules: { custom: true, custom_func: myCustomCheck } }
                ],
                altRows: true,
                rowNum: 10,
                rowList: [10, 20],
                pager: '#pager',
                gridview: true,
                rownumbers: true,
                autoencode: true,
                ignoreCase: true,
                sortname: 'invdate',
                viewrecords: true,
                sortorder: 'desc',
                footerrow: true,
                emptyrecords:"There are **no records added",
                caption: '',
                height: '100%',
                editurl: 'clientArray',
                ondblClickRow: function (rowid, ri, ci) {
                    var $this = $(this), p = this.p;
                    if (p.selrow !== rowid) {
                        // prevent the row from be unselected on double-click
                        // the implementation is for "multiselect:false" which we use,
                        // but one can easy modify the code for "multiselect:true"
                        $this.jqGrid('setSelection', rowid);
                    }
                    $this.jqGrid('editGridRow', rowid, editSettings);
                },
                onSelectRow: function (id) {
                    if (id && id !== lastSel) {
                        // cancel editing of the previous selected row if it was in editing state.
                        // jqGrid hold intern savedRow array inside of jqGrid object,
                        // so it is safe to call restoreRow method with any id parameter
                        // if jqGrid not in editing state
                        if (typeof lastSel !== "undefined") {
                            $(this).jqGrid('restoreRow', lastSel);
                        }
                        lastSel = id;
                    }
                }
            }).jqGrid('navGrid', '#pager', {edit:false,add:true, del:true, search:false, refresh:false}, editSettings, addSettings, delSettings,
                { multipleSearch: true, overlay: false,
                    onClose: function (form) {
                        // if we close the search dialog during the datapicker are opened
                        // the datepicker will stay opened. To fix this we have to hide
                        // the div used by datepicker
                        $("div#ui-datepicker-div.ui-datepicker").hide();
                    }
                });
4

1 回答 1

0

回调beforeSubmit确实触发了,但仅在成功验证的情况下。

您使用自定义验证的方式是错误的。例如,如果您检查值,如果公司已满,contractor您将收到错误消息事件。"Company/State ID/End Date is needed for a Contractor"问题是field2您在列myCustomCheck验证期间设置的变量将在验证将使用的位置之后设置。'compname''contractor'field2

如果您需要实现多个字段的自定义验证,则最好使用beforeCheckValues回调。回调将在所有其他验证之前调用。postdata所有字段作为输入。因此,您可以轻松验证数据。回调不能有任何return(或使用return;没有任何值)。您可以添加custom: true, custom_func 只有一列的验证规则。如果在回调[false, errorMessage]中发现验证错误,您可以在验证函数内部返回。beforeCheckValues

此外,我不建议您. $(function () {...});您应该将所有代码放在其中。这样您将减少全局变量的数量。

于 2013-03-21T17:07:59.093 回答