This question is similar to Custom aggregation/grouping in jqGrid but a little bit different.
I have the following jqGrid.
I find your question interesting. Moreover because you spend almost all your reputation points for the bounty I decided that you really need the solution of the problem. So I made the following demo for you. At the start it displays the full grid without grouping:
With respect of the select element you can choose the grouping column and receive as the result like
or
depend on the choice in the select element. If you choose "No grouping" the original view of the grid will be restored.
For the implementation I used groupSummary
with the custom implementation of summaryType.
I recommend you to read the answer additionally which describes how one can customize the summary row of the grouping.
The HTML code of body of the demo is
The corresponding the JavaScript code is below:
var intTemplate = { formatter: 'integer', align: 'right', sorttype: 'int',
summaryType: 'sum'},
grouppingTemplate = {
summaryType: function (val, name, record) {
if (typeof (val) === "string") {
return record[name];
}
return val;
}
},
$grid = $("#grid");
$grid.jqGrid({
url: 'CustomGrouping2.xml',
height: 'auto',
colModel: [
{ name: 'Level', formatter: 'integer', sorttype: 'int', template: grouppingTemplate },
{ name: 'State', template: grouppingTemplate },
{ name: 'City', template: grouppingTemplate },
{ name: 'Number1', template: intTemplate },
{ name: 'Number2', template: intTemplate },
{ name: 'Number3', template: intTemplate },
{ name: 'Selected', template: intTemplate }
],
cmTemplate: { width: 90 },
xmlReader: { root: 'result' },
loadonce: true,
rowNum: 1000,
grouping: false,
groupingView: {
groupField: ['State'],
groupSummary: [true],
groupColumnShow: [true],
groupText: ['{0}'],
groupDataSorted: true,
showSummaryOnHide: true
},
loadComplete: function () {
if (this.p.grouping) {
$(this).children('tbody').children('tr').each(function () {
var $tr = $(this);
if (!$tr.hasClass('jqfoot')) {
$tr.hide();
}
});
}
}
});
$('#chooseGrouping').change(function () {
var index, count, sel = $('option:selected', this).val(),
allGroups = ["State", "City", "Level"];
if (sel === "") {
$grid.jqGrid('setGridParam', {grouping: false});
for (index = 0, count = allGroups.length; index < count; index++) {
$grid.jqGrid('showCol', allGroups[index]);
}
} else {
$grid.jqGrid('setGridParam', {grouping: true, groupingView: {groupField: [sel]}});
$grid.jqGrid('showCol', sel);
index = $.inArray(sel, allGroups);
if (index >= 0) {
allGroups.splice(index, 1);
for (index = 0, count = allGroups.length; index < count; index++) {
$grid.jqGrid('hideCol', allGroups[index]);
}
}
}
$grid.trigger('reloadGrid');
});