0

I'm using free-jqgrid. i have a nested jqgrid inside another jqgrid (i.e subgrid) with multi-select. I have grouped the parent grid and the grouping works fine. However, when i set the groupCollapse: true, the subgrids remain expanded. Please see the code i have attached and let me know whats missing. expanded view

group collapsed but subgrid still shows

Function to load parent grid (with grouping)

function LoadActivities() {
if (typeof (showRPMLogFrame) != 'undefined' && showRPMLogFrame.toLowerCase() == true.toString().toLowerCase()) {
    //create custom object to bind to jqgrid
    var arrNewActivities = [];
    var clusterId;
    var cluster;
    var actId;
    var actDesc;
    var isCustomActivity;

    $("select[id*='drpCluster'] option:not(:first)").each(function () {
        clusterId = $(this).val();
        cluster = $(this).text();
        GetSelectedClusterId($(this).text());
        var arrActivities = [];
        //get the json data for activities
        $.ajax
           ({
               type: "POST",
               url: 'url',
               cache: false,
               async: false,
               data: '{"appealId" : "' + appealId + '", "projectId" :"' + (projectId == "" ? "0" : projectId) + '", "clusterId" : "' + clusterId + '", "rpmClusterId" : "' + selectedClusterId + '"}',
               dataType: 'json',
               contentType: "application/json; charset=utf-8",
               success: function (arr, status) {
                   arrActivities = arr;
                   for (i = 0; i < arrActivities.d.length; i++) {
                       actId = arrActivities.d[i].id;
                       actDesc = arrActivities.d[i].description;
                       arrNewActivities.push({
                           "clusterId": clusterId,
                           "cluster": cluster,
                           "id": actId,
                           "description": actDesc,
                           "isCustomActivity": false,
                           "isSaved": false
                       });
                   }
               },
               error: function (request, status, error) {
                   alert('Error in fetching RPM cluster mapped to OPS cluster : ' + cluster + '/n ' + error);
                   return false;
               }
           });
    });

    //gets the activities from database
    $.ajax({
        type: "POST",
        url: 'database webmethod url',
        cache: false,
        async: false,
        data: '{"projectId" :"' + (projectId == "" ? "0" : projectId) + '"}',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (arr, status) {

            for (i = 0; i < arr.d.length; i++) {
                for (j = 0; j < arrNewActivities.length; j++) {
                    if (arr.d[i].id == arrNewActivities[j].id) {
                        arrNewActivities[j].isCustomActivity = arr.d[i].IsCustomActivity;
                        arrNewActivities[j].isSaved = arr.d[i].IsSaved;
                    }
                }
            }
        },
        error: function (request, status, error) {
            alert('Error in loading saved activities for : ' + $(this).text() + '/n ' + error);
            return false;
        }
    });

    $("input[type='hidden'][id*='hdnSelectedActivities']").val(JSON.stringify(arrNewActivities));

    $("#tblGrid").jqGrid('GridUnload');

    "use strict";
    $("#tblGrid").jqGrid({
        mtype: "GET",
        datatype: "local",
        data: arrNewActivities,
        colModel: [
            { label: "Activity Id", name: "id", key: true, hidden: true },
            { label: "Cluster Id", name: "clusterId", hidden: true },
            { label: "Cluster", name: "cluster", hidden:true, width: 50, cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' } },
            {
                label: "Activity description", name: "description", required: true, editable: true, wrap: true, edittype: 'textarea', editoptions: { size: 300, maxlength: 2000 },
                cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }
            }
        ],
        multiselect: true,
        width: 700,
        shrinktofit: false,
        wrap: true,
        loadtext: "Loading...",
        emptyrecords: "No activities found.",
        //editurl: OPSServicePath + "/SaveActivity",
        onSelectRow: function (id) {
            SaveGrid();
        },
        subGrid: true, // set the subGrid property to true to show expand buttons for each row
        subgridtype: 'local', // set the subgrid type to json
        subGridRowExpanded: ShowChildGrid,
        // description of the subgrid model
        subGridModel: [{
            name: ["IndicatorId", "IndicatorTitle", "Cluster Target", "Project Target"],
            //width: [50, 500, 200],
            align: ["left", "left", "right", "right"],
            params: false
        }],
        pager: "#jqGridPager",
        viewrecords: false,
        pgtext: "",
        pgbuttons: false,
        pginput: false,
        gridComplete: function () {
            //hide select all checkbox in main grid
            $("#cb_tblGrid").hide();
            var rowIds = $("#tblGrid").getDataIDs();
            $.each(rowIds, function (index, rowId) {
                var arrActivities = $("#tblGrid").jqGrid("getGridParam", "data");
                var activity = $.grep(arrActivities, function (v) {
                    if (v.id == rowId) {
                        return v;
                    }
                });
                //expand activities that were saved in database
                if (activity[0].isSaved == true) {
                    $("#tblGrid").expandSubGridRow(rowId);
                    $("#tblGrid").setSelection(rowId, true);
                }

            });
        },
        grouping: true,
        groupingView: {
            groupField: ["cluster"],
            groupColumnShow: [false],
            groupText: ["<b>{0}</b>"],
            groupOrder: ["asc"],
            groupSummary: [false],
            groupSummaryPos: ['header'],
            groupCollapse: true
        }
    });

    $('#tblGrid').inlineNav('#jqGridPager',
        // the buttons to appear on the toolbar of the grid
        {
            view: false,
            edit: false,
            add: false,
            del: false,
            save: false,
            savetext: 'Save activity',
            cancel: true,
            editParams: {
                keys: true,
            },
            addParams: {
                keys: true
            },

        });

    //hide select all checkbox in main grid
    $("#cb_tblGrid").hide();
}

}

Function to load subgrid

function ShowChildGrid(parentRowID, parentRowKey) {
var arrIndicators = [];

//get the json data for activities
$.ajax
   ({
       type: "POST",
       url: 'child grid data api url',
       data: '{"projectId" : "' + (projectId == "" ? "0" : projectId) + '", "activityId" : "' + parentRowKey + '"}',
       dataType: 'json',
       contentType: "application/json; charset=utf-8",
       async: false,
       cache: false,
       success: function (arr, status) {
           if (typeof (arr) != 'undefined' && arr.d.length > 0) {
               for (i = 0; i <= arr.d.length - 1; i++) {
                   arrIndicators.push({
                       "IndicatorId": arr.d[i].IndicatorId,
                       "IndicatorTitle": arr.d[i].IndicatorTitle,
                       "Target": arr.d[i].Target,
                       "ProjectTarget": arr.d[i].ProjectTarget,
                       "IsCustomIndicator": arr.d[i].IsCustomIndicator,
                       "IsSaved": arr.d[i].IsSaved
                   });
               }
           }
       },
       error: function (request, status, error) {
           alert('Error in fetching RPM indicators mapped to activity : ');
           return false;
       }
   });

var childGridID = parentRowID + "_table";
var childGridPagerID = parentRowID + "_pager";

// send the parent row primary key to the server so that we know which grid to show
var childGridURL = parentRowKey + ".json";

// add a table and pager HTML elements to the parent grid row - we will render the child grid here
$('#' + parentRowID).append('<table id=' + childGridID + '></table><div id=' + childGridPagerID + ' class=scroll></div>');

$("#" + childGridID).jqGrid({
    //url: childGridURL,
    mtype: "GET",
    datatype: "local",
    data: arrIndicators,
    page: 1,
    multiselect: true,
    multiboxonly: true,
    colModel: [
        { label: 'Indicator ID', name: 'IndicatorId', key: true, hidden: true },
        { label: 'Indicator Title', name: 'IndicatorTitle', shrinkToFit: true, width: 300, editable: true, editrules: { required: true }, wrap: true, cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' } },
        { label: 'Cluster Target', name: 'Target', editable: false, shrinkToFit: true, width: 100, editrules: { required: true }, wrap: true },
        {
            label: 'Project Target', name: 'ProjectTarget', editable: true, shrinkToFit: true, width: 100, editrules: { required: true }, wrap: true, formatter: function (cellValue, option) {
                return '<input type="text" size="7" name="txtProjectTarget" onblur="CheckInput(this.id);" id="txtProjectTarget_' + option.rowId + '" />';
            }
        }
    ],
    onSelectRow: function (id) {
        SaveGrid();
    },
    loadonce: true,
    autowidth: true,
    loadtext: "Loading indicators...",
    emptyrecords: "No indicators found.",
    shrinktofit: true,
    height: '100%',
    pager: "#" + childGridPagerID,
    viewrecords: false,
    pgtext: "",
    pgbuttons: false,
    pginput: false,
    beforeSelectRow: function (rowId, e) {
        return $(e.target).is("input:checkbox");
    },
    gridComplete: function () {
        //hide select all checkbox in subgrids
        $("input[type='checkbox'][id*='cb_tblGrid_']").hide();
        var rowIds = $("#" + childGridID).getDataIDs();
        $.each(rowIds, function (i, rowId) {
            var arrIndicators = $("#" + childGridID).jqGrid("getGridParam", "data");
            var indicator = $.grep(arrIndicators, function (v) {
                if (v.IndicatorId == rowId) {
                    return v;
                }
            });
            if (indicator[0].IsSaved == true) {
                $("#" + childGridID).setSelection(rowId, true);
                $("#txtProjectTarget_" + indicator[0].IndicatorId).val(indicator[0].ProjectTarget)
            }

        });
    }
});

$("#" + childGridID).inlineNav("#" + childGridPagerID,
   {
       view: false,
       edit: false,
       add: false,
       del: false,
       cancel: false,
       save: false

   });

//hide select all checkbox in subgrids
$("input[type='checkbox'][id*='cb_tblGrid_']").hide();


//get parent row ID only
var parentRow = parentRowID.toString().split("_", 10)[1].toString();

//bind click event to checkboxes inside subgrid
$("#" + childGridID).find($("input[type='checkbox'][id*='jqg_tblGrid_" + parentRow + "_']")).each(function () {
    $(this).on("click", "", function () {
        //alert($(this).prop("id"));

        //check/uncheck the parent row checkbox if child grid checkboxes are checked/unchecked
        var parentTr = $("table#tblGrid tr#" + parentRow);
        if (typeof (parentTr) != "undefined") {
            var isChecked = $(this).prop("checked");
            //if current checkbox is checked, check parent row checkbox; if current checkbox is unchecked, do nothing to parent row checkbox 
            if (isChecked) {
                parentTr.find($("input[type='checkbox'][id='jqg_tblGrid_" + parentRow + "']")).prop("checked", isChecked);
                var selRowIds = $("#tblGrid").jqGrid("getGridParam", "selarrrow");
                if ($.inArray(parentRowKey, selRowIds) == -1 || selRowIds.length == 0) {
                    $("#tblGrid").setSelection(parentRowKey, true);
                }
            }
        }
    });
});

}

Dmitry
  • 6,716
  • 14
  • 37
  • 39
  • Just to add to the scenario.. this occurs only on document.ready(). Once loaded, on expanding and collapsing the groups manually, the subgrids are hidden as well (as expected). – codenamekarna Sep 25 '17 at 10:28
  • Could you provide **the demo**, which can be used to reproduce and to debug the problem? Please use non-minimized version of jqGrid (for example `https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js`) in the demo. Please include always in the text of your question **the exact version number** of free jqGrid, which you use. – Oleg Sep 25 '17 at 11:10
  • @Oleg, I have attached the demo you had asked. Sorry for the haphazard way of answering to the comments... this is my first post on the forum. – codenamekarna Sep 26 '17 at 07:51
  • Welcome on stackowerflow! First of all some common advices: You should think always about other visitors of the page (your question). Don't post additional information about the problem as new question. Instead of that click on "edit" link below the text of your question and **modify** your old text. It's good to append the text with words like "UPDATED" and additional information. If you need to upload VisualStudio project then you should **remove** `packages` folder and both `bin` and `obj` folders. Visual Studio will automatically restore all missing files. It reduce the size of zip file. – Oleg Sep 26 '17 at 09:53
  • In the most cases you can separate backend problems (your C# code) from JavaScript code (inclusive jqGrid). JSFiddle has [Echo service](http://doc.jsfiddle.net/use/echo.html#json), which allows to simulate loading of data from the server. See [the answer](https://stackoverflow.com/a/26001147/315935) or [another one](https://stackoverflow.com/a/46330312/315935) with the corresponding demos. – Oleg Sep 26 '17 at 09:57
  • About your main problem: I'm not sure which scenario you try to implement. What behavior you want to have? If you just remove `gridComplete` callbacks, which you use currently, then the grid will be displayed with collapsed groups. – Oleg Sep 26 '17 at 09:59
  • The last common advice. The main goal of stackoverflow: sharing **common** questions/problems with the corresponding solutions with other developers. Thus your should try to reduce or rewrite your existing code to make it shorter. Debugging of your existing code is out of scope of stackoverflow. You should try to post the questions so that there have **move value for other developers**. Short and clear code fragments with online demos (in JSFiddle, for example) are mostly helpful for other visitors of your question. – Oleg Sep 26 '17 at 10:13

1 Answers1

0

I'm attaching the demo as you had asked. Also I'm using free-jqgrid version 4.14.1.

https://drive.google.com/open?id=0BxSYIVU7orSuaE9VM052VlFKSUE