free-jqgrid / jqGrid

jQuery grid plugin
https://github.com/free-jqgrid/jqGrid
Other
480 stars 195 forks source link

How do I select only the filtered rows in jQgrid? #421

Open reypm opened 6 years ago

reypm commented 6 years ago

I have a grid (made with jqGrid 4.15.2). The code looks like the one below:

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

$(function () {
    "use strict";

    var $grid = $("#list"),
        maximizeGrid = function () {
            var newWidth = $grid.closest(".ui-jqgrid").parent().width();
            $grid.jqGrid("setGridWidth", newWidth, true);
        };

    // Resize grid if window is being resized
    $(window).on("resize", maximizeGrid);

    $grid.jqGrid({
        colNames: ["", "Form #", "Form", "Plan", "Class", "Drug"],
        colModel: [
            {name: "act", template: "actions"},
            {
                name: "FormId",
                align: 'center',
                fixed: true,
                frozen: true,
                resizable: false,
                width: 100,
                editable: "hidden"
            },
            {name: "FormName", search: true, stype: "text"},
            {name: "PlanName", search: true, stype: "text"},
            {
                name: "DrugGroupName",
                edittype: "select",
                editable: true,
                search: true,
                editoptions: {
                    dataUrl: "/ajax/drug_groups/get_all",
                    buildSelect: function (data) {
                        var select = "<select>", i;
                        for (i = 0; i < data.length; i++) {
                            select += "<option value='" + String(data[i].Id) + "'>" + $.jgrid.htmlEncode(data[i].DrugGroupName) + "</option>"
                        }

                        return select + "</select>";
                    },
                    selectFilled: function (options) {
                        setTimeout(function () {
                            $(options.elem).select2({
                                width: "100%"
                            });
                        }, 0);
                    }
                },
                stype: "select", searchoptions: {
                    sopt: ["eq", "ne"],
                    generateValue: true,
                    noFilterText: "Any",
                    selectFilled: function (options) {
                        setTimeout(function () {
                            $(options.elem).select2({
                                width: "100%"
                            });
                        }, 0);
                    }
                }
            },
            {name: "DrugName", search: true, stype: "text"}
        ],
        cmTemplate: {
            width: 300,
            autoResizable: true
        },
        iconSet: "fontAwesome",
        rowNum: 25,
        guiStyle: "bootstrap",
        autoResizing: {
            compact: true,
            resetWidthOrg: true
        },
        rowList: [25, 50, 100, "10000:All"],
        toolbar: [true, "top"],
        viewrecords: true,
        autoencode: true,
        sortable: true,
        pager: true,
        toppager: true,
        cloneToTop: true,
        hoverrows: true,
        multiselect: true,
        multiPageSelection: true,
        rownumbers: true,
        sortname: "Id",
        sortorder: "desc",
        loadonce: true,
        autowidth: true,
        autoresizeOnLoad: true,
        forceClientSorting: true,
        prmNames: {id: "Id"},
        jsonReader: {id: "Id"},
        url: '/ajax/plans_to_forms/get_all',
        datatype: "json",
        editurl: '/ajax/plans_to_forms/update',
        formDeleting: {
            url: '/ajax/plans_to_forms/delete/',
            delicon: [true, "left", "fa-scissors"],
            cancelicon: [true, "left", "fa-times"],
            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");

                $form.closest(".ui-jqdialog").position({
                    of: window,
                    my: "center center",
                    at: "center center"
                });

                if (rowids.length > 1) {
                    $form.find("td.delmsg").html('Are you sure you want to delete all the selected form links?');
                }
            },
            afterComplete: function (response, postdata, formid) {
                if (response.responseText === "true") {
                    toastr["success"]("The link was deleted successfully.", "Information");
                } else {
                    toastr["error"]("Something went wrong, the link could not be deleted.", "Error");
                }
            }
        },
        ajaxSelectOptions: {
            type: "POST",
            dataType: "json"
        },
        navOptions: {
            edit: false,
            add: false,
            search: false
        },
        inlineEditing: {
            keys: true,
            focusField: "DrugGroupName",
            serializeSaveData: function (postData) {
                var changedData = {}, prop, p = $(this).jqGrid("getGridParam"),
                    idname = p.keyName || p.prmNames.id,
                    oldValue, cm;

                for (prop in postData) {
                    oldValue = p.savedRow[0][prop];
                    if (p.iColByName[prop] != null) {
                        cm = p.colModel[p.iColByName[prop]];
                    }

                    if (postData.hasOwnProperty(prop) && (postData[prop] !== oldValue || prop === idname)) {
                        changedData[prop] = postData[prop];
                    }
                }

                return changedData;
            },
            aftersavefunc: function () {
                toastr["success"]("The record was updated successfully.", "Information");
            },
            errorfunc: function () {
                toastr["error"]("Something went wrong, the record could not be updated.", "Error");
            }
        },
        onSelectRow: function (rowid, status, e) {
            var $self = $(this),
                $td = $(e.target).closest("tr.jqgrow>td"),
                p = $self.jqGrid("getGridParam"),
                savedRow = p.savedRow;

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

            if ($td.length > 0 && $td[0].cellIndex !== p.iColByName.act) {
                // don't start editing mode on click on "act" column
                $self.jqGrid("editRow", rowid);
            }
        },
        loadComplete: function () {
            var $self = $(this), p = $self.jqGrid("getGridParam");

            if (p.datatype === "json") {
                // recreate the toolbar because we use generateValue: true option in the toolbar
                $self.jqGrid("destroyFilterToolbar").jqGrid("filterToolbar");
            }
        }
    }).jqGrid('navGrid').jqGrid("filterToolbar").jqGrid('setFrozenColumns');

    // fill top toolbar
    $('#t_' + $.jgrid.jqID($grid[0].id)).append($("<div><label for=\"globalSearchText\">Global search in grid for:&nbsp;</label><input id=\"globalSearchText\" type=\"text\"></input>&nbsp;<button id=\"globalSearch\" type=\"button\">Search</button></div>"));

    $("#globalSearchText").keypress(function (e) {
        var key = e.charCode || e.keyCode || 0;
        if (key === $.ui.keyCode.ENTER) { // 13
            $("#globalSearch").click();
        }
    });

    $("#globalSearch").button({
        icons: {primary: "ui-icon-search"},
        text: false
    }).click(function () {
        var postData = $grid.jqGrid("getGridParam", "postData"),
            colModel = $grid.jqGrid("getGridParam", "colModel"),
            rules = [],
            searchText = $("#globalSearchText").val(),
            l = colModel.length,
            i,
            cm;
        for (i = 0; i < l; i++) {
            cm = colModel[i];
            if (cm.search !== false && (cm.stype === undefined || cm.stype === "text")) {
                rules.push({
                    field: cm.name,
                    op: "cn",
                    data: searchText
                });
            }
        }
        postData.filters = JSON.stringify({
            groupOp: "OR",
            rules: rules
        });
        $grid.jqGrid("setGridParam", {search: true});
        $grid.trigger("reloadGrid", [{page: 1, current: true}]);

        return false;
    });
});

When I filter something and then want to mark the filtered results for delete all of them for some reason everything gets selected even those that hasn't been filtered which is sending all the IDs to the backend and therefore I am loosing everything when deleting based on the ID.

Maybe it's an stupid option or something else but I can't find what is wrong. Here is a video I have made showing up the issue. Here is a Fiddle for play with where you can see the issue happening

Steps to reproduce the issue:

Any ideas? Is this a bug?

OlegKi commented 6 years ago

Thanks for reporting the issue. I find the problem, which you describe, very interesting and thus I changed the default behavior of "Select All" button (checkbox) to select only currently filtered data (see the commit). The new option selectAllMode with the value "all" allows to have the old behavior.

reypm commented 6 years ago

@OlegKi thanks to you for fix this asap, should I close this one or you will do it when releasing a new version? speaking of which I have a concern, I am willing to think you keep BC on each new release but I might be wrong, so do you keep BC on new releases? It's safe to upgrade for newest version? Currently I am using 4.15.2 and was willing to upgrade to 4.15.3 but I was afraid of this.