如何在内联编辑后将数据发送到服务器?

问题描述 投票:0回答:1

我正在使用jQgrid Free(release 4.15.2),我需要添加编辑行内联的功能,这根本不是问题,因为它很容易设置。这是我正在使用的代码:

$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;

$(function () {
    "use strict";

    var $grid = $("#list"),
        pagerSelector = "#pager",
        customAddButton = function (options) {
            $grid.jqGrid('navButtonAdd', pagerSelector, options);
            $grid.jqGrid('navButtonAdd', '#' + $grid[0].id + "_toppager", options);
        };

    $.fn.fmatter.customActionsFormatter = function (cellValue, options, rowData) {
        return '<a href="#" title="Delete selected row"><span class="fa fa-fw fa-trash-o delete_row" data-id="' + rowData.Id + '"></span></a>';
    };

    $grid.jqGrid({
        url: '/ajax/plans_to_forms/get_all',
        datatype: "json",
        colNames: ["", "Id", "Form #", "Form", "Plan", "Class", "Drug"],
        colModel: [
            {name: "act", formatter: "customActionsFormatter", width: 20, search: false},
            {name: "Id", jsonmap: "Id", key: true, hidden: true},
            {name: "FormId", align: 'center', fixed: true, frozen: true, resizable: false, width: 100},
            {name: "FormName", width: 300},
            {name: "PlanName", width: 300},
            {name: "DrugGroupName", width: 300},
            {name: "DrugName", width: 300}
        ],
        cmTemplate: {autoResizable: true, editable: true},
        iconSet: "fontAwesome",
        rowNum: 25,
        guiStyle: "bootstrap",
        autoResizing: {compact: true},
        rowList: [25, 50, 100, "10000:All"],
        viewrecords: true,
        autoencode: true,
        sortable: true,
        pager: pagerSelector,
        toppager: true,
        cloneToTop: true,
        hoverrows: true,
        multiselect: true,
        multiPageSelection: true,
        rownumbers: true,
        sortname: "Id",
        sortorder: "desc",
        loadonce: true,
        autowidth: true,
        autoresizeOnLoad: true,
        forceClientSorting: true,
        shrinkToFit: true,
        navOptions: {
            edit: false,
            add: false,
            del: false,
            search: false
        },
        inlineEditing: {keys: true, defaultFocusField: "DrugGroupName", focusField: "DrugGroupName"},
        onSelectRow: function (rowid, status, e) {
            var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");

            if (savedRow.length > 0 && savedRow[0].id !== rowid) {
                $self.jqGrid("restoreRow", savedRow[0].id);
            }

            $self.jqGrid("editRow", rowid, {focusField: e.target});
        }
    }).jqGrid('navGrid', pagerSelector, {
        search: false,
        edit: false,
        add: false,
        del: false,
        refresh: true,
        cloneToTop: true
    }).jqGrid("filterToolbar", {
        stringResult: true, searchOnEnter: false, defaultSearch: 'cn'
    }).jqGrid("gridResize").jqGrid('setFrozenColumns');

    customAddButton({
        caption: 'Delete selected',
        buttonicon: 'fa-trash-o',
        title: "Delete all selected rows",
        onClickButton: function () {
            var rowIds = $("#list").jqGrid('getGridParam', 'selarrrow');

            if (rowIds.length > 0) {
                delete_all_link_modal.modal();
                delete_all_link_modal.attr('data-link-ids', rowIds);
            } else {
                alert('You must select at least one item.');
            }
        }
    });
});

以下行启用内联编辑:

inlineEditing: {keys: true, defaultFocusField: "DrugGroupName", focusField: "DrugGroupName"}

我的问题在哪里?我只需要编辑DrugGroupName列,上面的行使整行可编辑,这引出了以下问题:

  • 是否可以仅编辑一组给定的列而不是全部列? - 我正在检查文档here但我找不到任何有用的东西
  • 只要我点击任何其他地方或点击ENTER键,就可以将数据发送到服务器? - 我想避免额外点击保存图标。

更新:我已经找到了第一个问题的答案。我只需要在定义colModel时使列不可编辑。例如:

colModel: [
    {name: "act", formatter: "customActionsFormatter", width: 20, search: false},
    {name: "Id", jsonmap: "Id", key: true, hidden: true},
    {name: "FormId", align: 'center', fixed: true, frozen: true, resizable: false, width: 100, editable: false},
    {name: "FormName", width: 300, editable: false},
    {name: "PlanName", width: 300, editable: false},
    {
        name: "DrugGroupName",
        width: 300,
        edittype: "select",
        editoptions: {
            generateValue: true,
            selectFilled: function (options) {
                setTimeout(function () {
                    $(options.elem).select2({
                        width: "100%"
                    });
                }, 0);
            }
        },
        stype: "select", searchoptions: {
            sopt: ["eq", "ne"],
            generateValue: true,
            noFilterText: "Any",
            selectFilled: function (options) {
                $(options.elem).select2({
                    width: "100%"
                });
            }
        }
    },
    {name: "DrugName", width: 300, editable: false}
]

这样我就迫使DrugGroupName成为唯一一个可编辑的人。

javascript jquery jqgrid free-jqgrid
1个回答
1
投票

我认为你的代码有很多小问题。我准备了演示https://jsfiddle.net/OlegKi/rmo2370r/19/,它应该解决大多数问题并演示select2的使用和免费jqGrid的一些功能。

第一个小问题是使用正确的rowid。您使用当前隐藏的列

{name: "Id", jsonmap: "Id", key: true, hidden: true}

这是使用jqGrid的用户的典型误解。 Rowid将保存为行的id属性(<tr>元素)。见the picture。不需要将案例信息作为隐藏的<td>元素放置在网格内。而不是那个可以使用以下jqGrid选项

prmNames: { id: "Id" },
jsonReader: { id: "Id" },

代替。选项jsonReader.id通知jqGrid在填充网格时获取rowid的位置,prmNames.id在编辑网格时提供id的名称。

要在JSFiddle里面填充jqGrid,可以使用Echo服务:

url: '/echo/json/',
datatype: 'json',
mtype: 'POST', // required for '/echo/json/'
postData: {
    json: JSON.stringify(mydata)
},

对URL /echo/json/的请求将mydata作为响应。可以使用Chrome / IE / Firefox的开发人员工具的网络选项卡详细检查HTTP流量。

以同样的方式可以使用

editurl: '/echo/json/',
formDeleting: {
    url: '/echo/json/',
    ...
}

用于内联编辑和表单删除。

接下来的变化。我在resetWidthOrg: true中添加了autoResizing属性:

autoResizing: {
    compact: true,
    resetWidthOrg: true
}

这改变了与autowidth: true结合使用autoresizeOnLoad: true的结果。您可以看到所有列的宽度都比以前更好地基于列的内容。有关详细信息,请参阅the issues

我不明白customActionsFormatter的目标。我将其替换为标准格式化程序操作

{ name: "act", template: "actions" }

如果需要,免费的jqGrid可以非常容易地自定义动作按钮。有关详细信息,请参阅the answerthe wiki article

你的旧代码使用

cmTemplate: {
  autoResizable: true,
  editable: true
}

并在大多数列中设置editable: false。而不是你需要从editable: true中删除cmTemplate,只需要在一列中添加editable: true,你需要编辑它,并在cmTemplate中包含colModel中常用的其他设置:

cmTemplate: {
    width: 300,
    autoResizable: true
}

许多其他代码也可以简化。例如,请参阅onSelectRow的修改代码。

要自定义删除对话框,可以使用以下设置:

formDeleting: {
    url: '/echo/json/', // '/ajax/plans_to_forms/delete/' in final solution
    width: 320,
    caption: 'Delete Plan to Form Link',
    msg: 'Are you sure you want to delete this link?',
    beforeShowForm: function ($form) {
        var rowids = $form.find("#DelData>td").data("rowids");
            console.log(rowids);
            if (rowids.length > 1) {
            $form.find("td.delmsg")
                    .html('Are you sure you want to delete all the selected form links?');
            }
    }
}

删除将数据Id=20622,20626oper=del发送到服务器(formDeleting.url)。如果需要,可以使用serializeDelData将数据转换为JSON。

要在编辑期间将更多数据从列发送到服务器,可以在某些列中添加editable: "hidden"。我在演示的FormId列中添加了属性,并且在编辑期间发送到服务器的数据看起来像

{"FormId":"3393","DrugGroupName":"Some other value","oper":"edit","Id":"20620"}

要将<select>的数据填充到服务器的额外Ajax请求,需要使用editoptions.dataUrl。我在演示editoptions.postData中添加了仅模拟对服务器的实际请求:

editoptions: {
    dataUrl: "/echo/json/",
    postData: {
        json: JSON.stringify([
                "Non-Specialty Medications",
                "General Pharmacy Authorization",
                "Some other value"
            ])
        },
        buildSelect: function (data) {
            var select = "<select>", i;

            for (i = 0; i < data.length; i++) {
                select += "<option value='" + String(data[i]).replace(/\'/g, "&#39;") +
                            "'>" + $.jgrid.htmlEncode(data[i]) + "</option>"
            }
            return select + "</select>";
        },
        selectFilled: function(options) {
            var $self = $(this);

            setTimeout(function() {
                $(options.elem).select2({
                    width: "100%"
                }).on('select2:select', function (e) { 
                    // save the data on selection
                    $self.jqGrid("saveRow", options.rowid);
                });
            }, 0);
        }
    },
    stype: "select",
    searchoptions: {
        sopt: ["eq", "ne"],
        generateValue: true,
        noFilterText: "Any",
        selectFilled: function(options) {
            $(options.elem).select2({
                width: "100%"
            });
        }
    }
}

以上对dataUrl的请求返回JSON字符串[ "Non-Specialty Medications", "General Pharmacy Authorization", "Some other value" ]buildSelect将数据转换为HTML片段,<select>包含所有<options>。由此产生的<select>将在selectFilled回调中转换为select2 contril。最后代码使用

ajaxSelectOptions: {
    type: "POST",
    dataType: "json"
}

选项将Ajax请求的参数更改为dataUrl。演示https://jsfiddle.net/OlegKi/rmo2370r/19/包含一些其他的小改动,比如删除不需要的空的寻呼机div和pager: true的用法,就像你已经使用toppager: true一样。这是另一个功能,我在免费的jqGrid fork中实现,以简化jqGrid的使用。

© www.soinside.com 2019 - 2024. All rights reserved.