Несколько jqGrid на одной странице, как определить, на какой сетке нажать кнопку "Добавить" в навигаторе?

Страница, подобная http://trirand.com/blog/jqgrid/jqgrid.html Пример иерархии, но более сложная, для каждой сетки есть кнопки "Добавить". Когда пользователь нажимает кнопку "Добавить", нам нужно обрабатывать добавленные данные.,

Мы также ссылаемся на страницу http://www.ok-soft-gmbh.com/jqGrid/LocalFormEditing.htm для локального редактирования, соответствующий код приведен ниже:

jqGrid('navGrid','#pager',{},editSettings,addSettings,delSettings,
    {multipleSearch:true,overlay:false, null});

addSettings = {
   //recreateForm:true,
  jqModal:false,
  reloadAfterSubmit:false,
  savekey: [true,13],
  closeOnEscape:true,
  closeAfterAdd:true,
  onclickSubmit: function (options, postdata) {
      // expected to find grid id in options, but didn't find it.
  },

},

1 ответ

Я надеюсь, что я правильно понимаю ваш вопрос. Вы создаете несколько сеток на странице и добавляете панель навигации к сеткам. Ваша проблема, вероятно, была в старом коде упомянутой демонстрационной версии, которую я подготовил для старого ответа.

Ответ был написан во времена jqGrid версии 3.8.2. Позже код редактирования формы был изменен так, что this будет установлен на DOM текущей сетки редактирования внутри onclickSubmit как внутри всех других обратных вызовов jqGrid. Так что можно использовать $(this) для доступа к сетке. Более свежую демку, созданную для jqGrid 4.4.1, я выложил для ответа.

Я просмотрел код редактирования локального формата из двух упомянутых ответов, но текущая версия jqGrid (4.5.4) содержит больше изменений, необходимых для настройки кода. Так что я изменил мою демо еще раз. Получившаяся демоверсия, кажется, работает правильно в jqGrid 4.5.4. Это код, который я включаю ниже:

var mydata = [
        {id: "1",  invdate: "2013-11-01", name: "test",   note: "note",   amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00"},
        {id: "2",  invdate: "2013-11-02", name: "test2",  note: "note2",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00"},
        {id: "3",  invdate: "2013-09-01", name: "test3",  note: "note3",  amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00"},
        {id: "4",  invdate: "2013-11-04", name: "test4",  note: "note4",  amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00"},
        {id: "5",  invdate: "2013-11-31", name: "test5",  note: "note5",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00"},
        {id: "6",  invdate: "2013-09-06", name: "test6",  note: "note6",  amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00"},
        {id: "7",  invdate: "2013-11-04", name: "test7",  note: "note7",  amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00"},
        {id: "8",  invdate: "2013-11-03", name: "test8",  note: "note8",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00"},
        {id: "9",  invdate: "2013-09-01", name: "test9",  note: "note9",  amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00"},
        {id: "10", invdate: "2013-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true,  ship_via: "TN", total: "530.00"},
        {id: "11", invdate: "2013-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00"},
        {id: "12", invdate: "2013-09-10", name: "test12", note: "note12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00"}
    ],
    onclickSubmitLocal = function (options, postdata) {
        var $this = $(this), p = $(this).jqGrid("getGridParam"),// p = this.p,
            idname = p.prmNames.id,
            id = this.id,
            idInPostdata = id + "_id",
            rowid = postdata[idInPostdata],
            addMode = rowid === "_empty",
            oldValueOfSortColumn,
            newId,
            idOfTreeParentNode;

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

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

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

        // decode data if there encoded with autoencode
        if (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 = p.sortname === "" ? undefined : $this.jqGrid("getCell", rowid, p.sortname);

        // save the data in the grid
        if (p.treeGrid === true) {
            if (addMode) {
                $this.jqGrid("addChildNode", newId, p.selrow, postdata);
            } else {
                $this.jqGrid("setTreeRow", rowid, postdata);
            }
        } else {
            if (addMode) {
                $this.jqGrid("addRowData", newId, postdata, options.addedrow);
            } else {
                $this.jqGrid("setRowData", rowid, postdata);
            }
        }

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

        if (postdata[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;
        return {};
    },
    editSettings = {
        //recreateForm: true,
        jqModal: false,
        reloadAfterSubmit: false,
        closeOnEscape: true,
        savekey: [true, 13],
        closeAfterEdit: true,
        onclickSubmit: onclickSubmitLocal
    },
    addSettings = {
        //recreateForm: true,
        jqModal: false,
        reloadAfterSubmit: false,
        savekey: [true, 13],
        closeOnEscape: true,
        closeAfterAdd: 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), id = $.jgrid.jqID(this.id), p = this.p,
                newPage = 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 (p.treeGrid) {
                $this.jqGrid("delTreeNode", rowid);
            } else {
                $this.jqGrid("delRowData", rowid);
            }
            $.jgrid.hideModal("#delmod" + id, {
                gb: "#gbox_" + id,
                jqm: options.jqModal,
                onClose: options.onClose
            });

            if (p.lastpage > 1) {// on the multipage grid reload the grid
                if (p.reccount === 0 && newPage === 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",
                showOn: "button",
                changeYear: true,
                changeMonth: true,
                showButtonPanel: true,
                showWeek: true
            });
        }, 50);
    },
    initDateSearch = function (elem) {
        setTimeout(function () {
            $(elem).datepicker({
                dateFormat: "dd-M-yy",
                changeYear: true,
                changeMonth: true,
                showButtonPanel: true,
                showWeek: true
            });
        }, 50);
    },
    removeTheOptionAll = function (elem) {
        // We use "value" in the searchoption property of some columns of the colModel.
        // The option {"": "All"} neams "No filter" and should be displayed only
        // in the searching toolbar and not in the searching dialog.
        // So we use dataInit:removeTheOptionAll inside of searchoptions to remove
        // the option {"": "All"} in case of the searching dialog
        if (elem != null && typeof elem.id === "string") {
            if (elem.id.substr(0, 3) !== "gs_") {
                // we are NOT in the searching bar
                $(elem).find("option[value=\"\"]").remove();
            }
        }
    };

$("#list").jqGrid({
    datatype: "local",
    data: mydata,
    colNames: ["Client", "Date", "Amount", "Tax", "Total", "Closed", "Shipped via", "Notes"],
    colModel: [
        {name: "name", width: 60, editrules: {required: true}},
        {name: "invdate", width: 80, align: "center", sorttype: "date",
            formatter: "date", formatoptions: {newformat: "d-M-Y"},
            editoptions: {dataInit: initDateEdit, size: 14},
            searchoptions: {dataInit: initDateSearch}},
        {name: "amount", width: 70, formatter: "number", align: "right"},
        {name: "tax", width: 50, formatter: "number", align: "right"},
        {name: "total", width: 60, formatter: "number", align: "right"},
        {name: "closed", width: 70, align: "center", formatter: "checkbox",
            edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"},
            stype: "select",
            searchoptions: {
                sopt: ["eq", "ne"],
                value: ":All;true:Yes;false:No",
                dataInit: removeTheOptionAll
            }},
        {name: "ship_via", width: 100, align: "center", formatter: "select",
            edittype: "select", editoptions: {value: "FE:FedEx;TN:TNT;IN:Intim", defaultValue: "TN"},
            stype: "select",
            searchoptions: {
                sopt: ["eq", "ne"],
                value: ":All;FE:FedEx;TN:TNT;IN:Intim",
                dataInit: removeTheOptionAll
            }},
        {name: "note", width: 60, sortable: false, edittype: "textarea"}
    ],
    cmTemplate: {editable: true, searchoptions: {clearSearch: false }},
    rowNum: 10,
    rowList: [5, 10, 20],
    pager: "#pager",
    gridview: true,
    rownumbers: true,
    autoencode: true,
    ignoreCase: true,
    sortname: "invdate",
    viewrecords: true,
    sortorder: "desc",
    caption: "Demonstrates implementating of local form editing",
    height: "100%",
    editurl: "clientArray",
    ondblClickRow: function (rowid) {
        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);
    }
}).jqGrid("navGrid", "#pager", {}, editSettings, addSettings, delSettings, {
    multipleSearch: true,
    overlay: false,
    onClose: function () {
        // 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();
    }
}).jqGrid("filterToolbar", { defaultSearch: "cn" });
Другие вопросы по тегам