SPServices Stories #10 – jqGrid Implementation Using SPServices in SharePoint

This entry is part 10 of 21 in the series SPServices Stories

Introduction

Today’s SPServices Story comes from Prateek Kulkarni in Bengaluru, India. Prateek posted this originally on the C# Corner site as jqGrid Implementation Using SpServices in SharePoint.

As with several of the earlier SPServices Stories posts, I found this one interesting because it shows how to use SPServices with another framework to render the results obtained from the Web Services calls.

I’ve had several people tell me that there isn’t enough “story” to these SPServices Stories. Have a better one? Let me know!

jqGrid with SPServices

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

SPService 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 SPService and jQuery is best explained at Marc’s blog.

Following Js files are needed for JqGrid Implementation with SPService

  • jquery-1.8.2.js
  • grid.locale-en.js
  • jquery.jqGrid.min.js  // Structuring jqGrid
  • json2-min.js  // Parsing data to json format
  • jquery.SPServices-0.7.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 follows:

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;
  }

  //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

//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).SPFilterNode("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

Series Navigation<< SPServices Stories #9: Developing with Client-side Technologies: jQuery, REST, SPServices and jsRenderSPServices Stories #11 – Using SPServices and jQuery to Perform a Redirect from a SharePoint List NewForm to EditForm >>

Similar Posts

12 Comments

  1. Hi Marc,
    I’m using an array as datasource for my jqgrid, i’m also implementing groupby on my grid. This groupby is working fine in Firefox and Chrome, but in IE it’s not working. In IE grouping is there, but when i click on ‘+’ icon to expand my items,it’s showing no responce. Any help…

    1. Hi Karthik

      Please share me the exact code and the way how you are using the Group By.
      I have implemented the jqGrid, with sorting and paging function. So let me try to help you.

      Thanks
      Prateek

  2. Hi Marc,

    I have one requirement
    I have 1 list with key | Exchange Rate two columns
    List 1:
    key Exchange Rate
    A 0.5
    B 2
    C 2
    D 3

    >>>>>>>>>
    List 2: another list Amount List Key Amount
    key Amount
    A 1000 1000
    A 2000 2000
    B 3000 3000

    whenever users open any particular view (example test.apsx) of second list ( customized in SPD)
    I have to get below results depending upon the exchange rate defined in configuration list 1
    I,e exchange rate * Amount .. note: exchange rate always changes every 2 days. so runtime it has to multiple and show it in the any customized view

    key Amount
    A 500
    A 1000
    B 6000

    how can I do it through OOTB

  3. Hi Marc,
    I like these spservices-stories. But one thing that would make it easier for me, a visual learner, is to see the application in action. When I see it, I can follow the code better.
    thx

    1. Rich:

      That’s a great idea. In many cases, the stories are boiled down from in-place production systems. Those systems are behind firewalls and not readily visible to anyone. That said, I could try to include short videos in the future, where possible.

      M.

  4. I have not tried jqGrid but I have used jQuery Datatables extensively https://datatables.net/. In some cases I will just built the html table with the results from SPServices, other cases I will build a javascript object for the table.

    I have not looked in detail but it looks like you have a trailing comma in your JSON object. This will work in Chrome and FF but it will not work in IE <10. IE will throw a cryptic error (can't remember at this time).

    You want your output to be like:

    {id:'10',cell:['10','Name','Manager']}

    Finally, a snippet of code I have been using (and I can't remember where I got it, maybe even you) was to map the entire result-set of attributes to a JavaScript array, this loops through all of the attributes and applies it to a name value pair and strips the ows_ from the name. The result is an array of results which you can call using the javascript dot notation.

    var navOptions = new Array();
    jQuery(xData.responseXML).SPFilterNode("z:row").each(function() {
    var item = jQuery(this);
    jQuery.each(this.attributes, function(i, attrib) {
    var name = attrib.name;
    var value = attrib.value;
    navigation[name.replace('ows_', '')] = value;
    });
    navOptions.push(navigation);
    navigation = {};
    });

    1. I know this is a very late response. But, im stuck with this

      thegrid.addJSONData(JSON.parse(newStr));

      its not binding the newStr value to the Grid. i’ve loaded the Json.min file correctly. But still, i’m not getting the result. Any suggestions ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.