0

Is there a way I can use custom formatter to format the grouptext value in jqgrid.

Current Output for var grouping=new Array("Environment", "System", "IIR","Userlimit","Kernel Parameters"); enter image description here Suppose I have these groups.

var grouping=new Array("3Environment", "0System", "4IIR","2Userlimit","1Kernel Parameters");

If I sort it in ascending order it should display System, Kernel, Userlimit, Environment, IIR i.e., using some kind of custom formatter remove 01234 from 1st character or similar to sort my groups in some already decided order.

jqGrid Code

$('#compareContent').empty();
        $('<div id="compareParentDiv" width="100%">'+
          '<table id="list2" cellspacing="0" cellpadding="0"></table>'+
                '<div id="gridpager3"></div></div>')
        .appendTo('#compareContent');

        $("#compareParentDiv").hide();

        var gridDiff = $("#list2");
        gridDiff.jqGrid({
            datastr: compareData,
            datatype: "jsonstring",
            colNames: ['KeyName', 'SubCategory', starheader, header1,'isEqual'],
            colModel: [
                { name: 'elementName', index: 'elementName', key: true, width: 120 },
                { name: 'subCategory', index: 'subCategory', width: 1 },
                { name: 'firstValue', index: 'firstValue', width: 310, jsonmap:'attribute.0.firstValue' },
                { name: 'secondValue', index: 'secondValue', width: 310,jsonmap:'attribute.0.secondValue' },
                { name: 'isEqual', index: 'isEqual', width: 1,hidden:true}
            ],
            pager: '#gridpager3',
            rowNum:60,
            scrollOffset:1,
            //viewrecords: true,
            jsonReader: {
                repeatitems: false,
                page: function(){return 1;},
                root: "response"
            },
            //rownumbers: true,

            height: '320',
            autowidth:true,
            grouping: true,

            groupingView: {
                groupField: ['subCategory'],
                groupOrder: ['desc'],
                groupDataSorted : false,
                groupColumnShow: [false],
                //groupCollapse: true,
                groupText: ['<b>{0}</b>']

            },

            loadComplete: function() {
                if (this.p.datatype !== 'local') {
                    setTimeout(function () {
                       gridDiff.trigger('reloadGrid');
                   }, 0);
                } else {
                    $("#compareParentDiv").show();
                }

                var i, names=this.p.groupingView.sortnames[0], l = names.length;
                 data = this.p.data, rows = this.rows, item;


                for (i=0;i<l;i++) {
                    if ($.inArray(names[i],grouping) >= 0) {

                        $(this).jqGrid('groupingToggle',this.id+"ghead_"+i);

                        $(rows.namedItem(this.id+"ghead_"+i)).find("span.ui-icon").click(function(){
                            var len = data.length, iRow;
                            for (iRow=0;iRow<len;iRow++) {
                                item = data[iRow];
                                if (item.isEqual) {
                                    $(rows.namedItem(item._id_)).hide();
                                }
                            }
                        });

                    } else {
                        // hide the grouping row
                        $('#'+this.id+"ghead_"+i).hide();
                    }
                    //console.info($('#'+this.id+"ghead_"+i));
                }

                var i, names=this.p.groupingView.sortnames[0], l = names.length,
                data = this.p.data, rows = this.rows, item; 

                l = data.length;
                for (i=0;i<l;i++) {
                    item = data[i];
                    if (!item.isEqual) {
                        $(rows.namedItem(item._id_))
                            .css({
                                "background-color": "#FFE3EA",
                                "background-image": "none"
                            });
                    } else {
                        $(rows.namedItem(item._id_)).hide();
                    }
                }
            }
        });
        gridDiff.jqGrid('navGrid', '#gridpager3', { add: false, edit: false, del: false, search: false, refresh: false });
        gridDiff.jqGrid('navButtonAdd',"#gridpager3",{caption:"Toggle",title:"Toggle Search Toolbar", buttonicon :'ui-icon-pin-s',
            onClickButton:function(){
                gridDiff[0].toggleToolbar();
            } 
        });
        gridDiff.jqGrid('navButtonAdd',"#gridpager3",{caption:"Clear",title:"Clear Search",buttonicon :'ui-icon-refresh',
            onClickButton:function(){
                gridDiff[0].clearToolbar();
            } 
        });
        gridDiff.jqGrid('filterToolbar',
                {stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});

Update

Or is there a way to use positioning to place each grouped item, if sorting is not an option

Updated after accepting answer by Oleg

Page1 Page1

Page3 Page3

AabinGunz
  • 12,109
  • 54
  • 146
  • 218

1 Answers1

1

It seems to me that you have not the problem with the custom formatter of the grouptext

You use groupingView having groupDataSorted: false so the sorting of the group (in your case groupField: ['subCategory'] with groupOrder: ['asc']) do jqGrid for you. So the standard sorting behavior will be used.

jqGrid supports sorttype property of the colModel which define how the column should be sorted. If you need custom sorting order you should define sorttype property as a function which returns integer or string used instead of the cell value from the column. the prototype of the sorttype function could be function(cellValue,rowData) so it is possible to define the order which not only the cell value of the sorted column will be used but the whole contain of the row inclusive _id_ property. In you case the usage of the first cellValue parameter would be enough.

So to solve you problem you can for example define an array with the order of 'subCategory' values which you need:

var orderOfSubCategory = [
    "System", "system", "Kernel", "Kernel Parameters", "Userlimit",
    "Environment", "IIR", "Product"
];

and then define 'subCategory' column as following:

{
    name: 'subCategory',
    index: 'subCategory',
    width: 1,
    sorttype: function (value) {
        return $.inArray(value, orderOfSubCategory);
    }
}

You should don't forget, that jQuery.inArray return 0-based index of the item or -1 if the item will be not found in the array. So the values of 'subCategory' which could be not found in the orderOfSubCategory array will be placed the first. See here the corresponding demo.

Some other small remarks about your code. You use new Array(...) which is bad practice in JavaScript instead of that you should use always [...] construct which do the same is shorter and work quickly. Example: var grouping = ["Environment", "System", "IIR","Userlimit","Kernel Parameters"];

Another place which is difficult for to read for me is:

$('#compareContent').empty();
$('<div id="compareParentDiv" width="100%">'+
  '<table id="list2" cellspacing="0" cellpadding="0"></table>'+
        '<div id="gridpager3"></div></div>')
    .appendTo('#compareContent');
$("#compareParentDiv").hide();

Here you first use cellspacing="0" cellpadding="0" attributes of the table which are unneeded and seconds use empty(), append() combination instead of one html() call. The following code do the same, but it seems me better:

$('#compareContent').html(
    '<div id="compareParentDiv" style="display: none" width="100%">' +
    '<table id="list2"></table><div id="gridpager3"></div></div>');
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Very nice explanation and approach. Thanks Oleg – AabinGunz Aug 05 '11 at 05:03
  • I am having one problem, after I add sorting from your answer, `IIR` goes to next page since `Environment` and others exceed `rowNum:60,` I wanted that when the user sees the grid 1st he is able to all the groupings, if not all then till the height of thr grid all the groupings should appear `height: '320',`. I also want paging, because `Environment` can have more than 100 values.. Any chance I can have such a solution? I added a screen shot – AabinGunz Aug 05 '11 at 05:24
  • @Abhishek Simon: If you would place in the data from the first page produced by the server at lease one item from **all** groups and use **server side paging** your new requirements could be implemented. If you don't want to have server side paging I see the usage of `rowNum:1000` as the only way. – Oleg Aug 05 '11 at 06:31
  • Can't we have some kind of positioning of the groups here ` var i, names=this.p.groupingView.sortnames[0], l = names.length; for (i=0;i= 0) { $(this).jqGrid('groupingToggle',this.id+"ghead_"+i); } else { // hide the grouping row $('#'+this.id+"ghead_"+i).hide(); } }` – AabinGunz Aug 05 '11 at 06:40
  • @@Abhishek Simon: Sorry, but I don't understand what kind of "positioning" you mean. You should understand, that in case of grouping there are exactly `rowNum` rows on the page. The rows with the data are just *hidden*. So the grouping headers of the rows on the current page could be only shown. – Oleg Aug 05 '11 at 06:46
  • thanks.. also by positioning I mean.. that System will come on 1st page's 0th location or row likewise, also if you are free please take a look at [this question](http://stackoverflow.com/questions/6939096/hide-grouping-heading-in-jqgrid-if-every-row-inside-it-is-hidden) – AabinGunz Aug 05 '11 at 06:53
  • Do you have any link that could give me an idea of server side pagination.. which will help me achieve solution to this question? – AabinGunz Aug 05 '11 at 07:46
  • @Abhishek Simon: The server code depends on the language (C#, Java, PHP, ...), technology (ASP.NET MVC, WCF, ...), database access technology (`SqlDataReader`, Entity Framework, LINQ to SQL ...), the database which you use (Microsoft SQL, MySQL, ...) and so on. So it's difficult to recommend you something without additional information. – Oleg Aug 05 '11 at 08:05
  • Please look at a similar [question here](http://stackoverflow.com/questions/9962931/jqgrid-sort-subgrid-values-based-on-some-key) – AabinGunz Apr 01 '12 at 09:00