Click here to Skip to main content
15,888,527 members
Articles / Programming Languages / Javascript

jqGrid Implementation using SpServices in SharePoint

Rate me:
Please Sign up or sign in to vote.
4.88/5 (5 votes)
14 Mar 2012CPOL2 min read 41.8K   6   11

Hi All, 

This article is regarding implementation of jqGrid(demo) using SpServices(CodePlex

As SpServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use. It also includes functions which use the various Web Service operations to provide more useful (and cool) capabilities. It works entirely client side and requires no server installation.

Use of SpServices and jQuery is best explained at Marc’s blog.

Following Js files are needed for JqGrid Implementation with SpServices

  • jquery.js 
  • jquery-ui-1.8.1.custom.min.js
  • grid.locale-en.js
  • jquery.jqGrid.min.js
  • json2-min.js// Parsing data to json format
  • jquery.SPServices-0.6.2.js// For getting the list items 

Css file required  

 ui.jqgrid.css//Style sheet of Grid 

HTML controls for jqGrid are as mentioned below. 

<div id='tblMain' style="float:left">
  <table  id="list" ></table>
  <div id="pager" style="text-align:center;"></div> 
</div> 

Loading JqGrid on the page load:

jQuery("#list").jqGrid({

  datatype: GetMyData, 
  colNames:["Project ID","Project Name","Delivery Manager","ApprovalStatus"],
  colModel:[{name:'ProjectId',index:'ProjectId',align:'left',sortable: true},
            {name:'ProjectName',index:'ProjectName',align:'left',sortable: true },
          {name:'DeliveryManager',index:'DeliveryManager',align:'left',sortable:true},
          {name:'ApprovalStatus',index:'ApprovalStatus',align: 'left',sortable: true }
                       ],
  pager: true,
  pager: '#pager', 
  pageinput: true,
  rowNum: 5,
  rowList: [5, 10, 20, 50, 100],
  sortname: 'ApprovalStatus',
  sortorder: "asc",
  viewrecords: true,
  autowidth: true,
  emptyrecords: "No records to view",
  loadtext: "Loading..."    
   });

In the above jqGrid load function I have mentioned the datatype for the grid as GetMyData() which is a function that gets triggerred first. 

The GetMyData method has function GetDataOnLoad which uses the SpServices which has the basic operation of getting the list items i.e. GetListItems, which need optional CAML Query property which will fetch the data from list with some WHERE clause.

In the code I have a list called ProjectDetailsList which will contain details of some projects which are inserted by some Project Manager or delivery manager. So the requirement was when a user log in to the system I should get the current login user name and pass the same user name to the “where” clause of query so the grid will contain data of projects to which the current logged in user is assigned as PM or DM.

To get the current login user am using SpServices Operation SpGetCurrentUser.

The method GetTheOrderByType function will make the query part for SpServices.

The functions code is as follwos:

function ForGettingUserName() {
            var userName = $().SPServices.SPGetCurrentUser({
                fieldName: "Title",
                debug: false
            });
            return userName;
        }
function GetMyData() {
            sortIdexName = jQuery("#list").getGridParam("sortname"); //Maintaining Consitant SortName after the Sortcol event 
            sortOrderName = jQuery("#list").getGridParam("sortorder"); //Maintaining Consistant Sort Order 
            Query = GetTheOrderByType(sortIdexName, sortOrderName);
            var CAMLViewFields = "<ViewFields>" +
                      +"<FieldRef Name='projectName' /><FieldRef Name='projectID' />"
                      + "<FieldRef Name='Title' /><FieldRef Name='deliveryManager' />"
                      + "<FieldRef Name='projectSQA' /><FieldRef Name='approvalStatus' />"
                    + "<FieldRef Name='projectStartDate' /><FieldRef Name='projectEndDate' />"
                      + "<FieldRef Name='sqasiteurl' /><FieldRef Name='ID' />"
                      + "</ViewFields>";
            GetDataOnLoad(Query, CAMLViewFields);
        } 
//Function for Getting the Query Type and the particular WHERE CLAUSE TO send the  Query to GetListItem function.   
 function GetTheOrderByType(index, sortOrder, userName) {
            var OrderByType;
if (index == "ProjectName") {
     if (sortOrder == "desc") {
OrderByType = "<Query>"+
             +"<Where><Or>"+"<Eq>"+"<FieldRef Name='deliveryManager'/><Value Type='Text'>" 
             + userName +"</Value>"+"</Eq>"
             +"<Eq><FieldRef Name='projectManager'/><Value Type='Text'>" 
             + userName + "</Value></Eq>"+"</Or></Where>"+ 
             +"<OrderBy><FieldRef  Name='projectName' Ascending='FALSE' /></OrderBy>"+
            +"</Query>"; 
} 
    else {    
OrderByType =  "<Query>"+
             +"<Where><Or>"+"<Eq>"+"<FieldRef Name='deliveryManager'/><Value Type='Text'>" 
             + userName +"</Value>"+"</Eq>"
             +"<Eq><FieldRef Name='projectManager'/><Value Type='Text'>" 
             + userName + "</Value></Eq>"+"</Or></Where>"+ 
             +"<OrderBy><FieldRef  Name='projectName' Ascending='FALSE' /></OrderBy>"+
            +"</Query>"; 
 }
}
 
 else if (index == "ApprovalStatus") {
      if (sortOrder == "desc") {
OrderByType =  "<Query>"+
             +"<Where><Or>"+"<Eq>"+"<FieldRef Name='deliveryManager'/><Value Type='Text'>" 
             + userName +"</Value>"+"</Eq>"
             +"<Eq><FieldRef Name='projectManager'/><Value Type='Text'>" 
             + userName + "</Value></Eq>"+"</Or></Where>"+ 
             +"<OrderBy><FieldRef  Name='approvalStatus' Ascending='FALSE' /></OrderBy>"+
            +"</Query>"; 
             } 
        else {  
 OrderByType = "<Query>"+
             +"<Where><Or>"+"<Eq>"+"<FieldRef Name='deliveryManager'/><Value Type='Text'>" 
             + userName +"</Value>"+"</Eq>"
             +"<Eq><FieldRef Name='projectManager'/><Value Type='Text'>" 
             + userName + "</Value></Eq>"+"</Or></Where>"+ 
             +"<OrderBy><FieldRef  Name='approvalStatus' Ascending='FALSE' /></OrderBy>"+
            +"</Query>";             
     }
       return OrderByType;
  }    
<pre>//This function gets the data from List using SpServices 
Function GetDataOnLoad (Query,CAMLViewFields) {
        $().SPServices({ 
                operation: "GetListItems",
                async: false,
                listName: "ProjectDetailsList",
                CAMLQuery: Query,
                CAMLViewFields: CAMLViewFields,
                completefunc: processResult 
            }); 
      }  

The processResult is the function which formats the data which can be converted to Json and adds to the JqGrid.

The reason of formatting of data in the following particular format is to make it readable by the Json parser which is json2.js file. I had implemented the same JqGrid in asp.net application with AJAX calls where it was returning the data in this format and some other bloggers also used the same data format in the MVC or asp.net application with the help for JsonHelper class which mainly formats the data returned from the DB <o:p> 

<pre>//Processing the XML result to formatted Json so that We can bind data to grid in Json format
        function processResult(xData, status) {
            var counter = 0; // Gets the total number of records retrieved from the list (We can also use xData.ItemCount method for counting the number of rows in the data )
            var newJqData = "";
            $(xData.responseXML).find("[nodeName='z:row']").each(function () {
                var JqData;
                if (counter == 0) {
                   JqData = "{id:'" + $(this).attr("ows_projectID") + "',"
                              + "cell:[" + "'" + $(this).attr("ows_projectID") + "','" +
                              $(this).attr("ows_projectName") + "','" +
                              $(this).attr("ows_deliveryManager") + "','," +
                              "]}";
                    newJqData = newJqData + JqData;
                    counter = counter + 1;
                }
                else {
                     var  JqData = "{id:'" + $(this).attr("ows_projectID") + "',"
                              + "cell:[" + "'" + $(this).attr("ows_projectID") + "','" +
                              $(this).attr("ows_projectName") + "','" +
                              $(this).attr("ows_deliveryManager") + "','," +
                              "]}";
                    newJqData = newJqData + JqData;
                    counter = counter + 1;
                }


            });
            FinalDataForGrid(newJqData, counter);
        }  
That’s it. Add the data to the grid with the div control and the other page number calculation is for showing the pager.
function FinalDataForGrid(jqData, resultCount) {
        dataFromList = jqData.substring(0, jqData.length - 1);
        var currentValue = jQuery("#list").getGridParam('rowNum');
        var totalPages = Math.ceil(resultCount / currentValue);
        var PageNumber = jQuery("#list").getGridParam("page"); // Current page number selected in the selection box of the JqGrid           
        //formatting rows 
        newStr = "{total:" + '"' + totalPages + '"' + "," + "page:" + '"' + PageNumber + '"' + ","
                  + "records:" + '"'
                  + resultCount + '"' + ","
                  + "rows:"
                  + "[" + dataFromList + "]}";
        var thegrid = jQuery("#list")[0]; 
        thegrid.addJSONData(JSON.parse(newStr)); //Binding data to the grid which is of JSON Format 
And the grid works fine and fast on paging, sorting and also even search, we can make the particular column as hyperlink which I will blog in the next part. Sample grid is as follows and this grid has some extra columns then the mentioned in above code    Thanks to Nagaraj My TL and Kamal Sir for the support... Enjoy SharePoint!!!!!!!! Check out my blog 
This article was originally posted at http://gulbargaprateek.blogspot.in

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Marlabs
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHere is a much better implementation Pin
RalphZero24-Jan-15 2:47
RalphZero24-Jan-15 2:47 
QuestionJSON.parse(newStr) not working Pin
Member 109918864-Aug-14 20:03
Member 109918864-Aug-14 20:03 
AnswerRe: JSON.parse(newStr) not working Pin
RalphZero21-Jan-15 3:29
RalphZero21-Jan-15 3:29 
GeneraljqGrid with listdata.svc Pin
russekk15-Jun-12 16:16
russekk15-Jun-12 16:16 
QuestionRead it tonite Pin
Rohit Singh201214-Mar-12 6:19
Rohit Singh201214-Mar-12 6:19 
QuestionWhy? Pin
#realJSOP12-Mar-12 23:34
mve#realJSOP12-Mar-12 23:34 
AnswerRe: Why? Pin
prateekkulkarni12-Mar-12 23:40
prateekkulkarni12-Mar-12 23:40 
Hi John
Thanks for the suggestion and i have made the necessary change.

Regards
Prateek
QuestionSome clean up... Pin
Dave Kreskowiak12-Mar-12 4:36
mveDave Kreskowiak12-Mar-12 4:36 
AnswerRe: Some clean up... Pin
prateekkulkarni12-Mar-12 19:09
prateekkulkarni12-Mar-12 19:09 
AnswerRe: Some clean up... Pin
prateekkulkarni12-Mar-12 19:17
prateekkulkarni12-Mar-12 19:17 
GeneralRe: Some clean up... Pin
Dave Kreskowiak13-Mar-12 8:52
mveDave Kreskowiak13-Mar-12 8:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.