SPServices.SPGetLastItemId can be used if the list being queried is using folders

Jul 16, 2010 at 11:33 AM

SPServices.SPGetLastItemId can be used if the list being queried is using folders.

I had a project where all lists on a site were useing Folders for Security and Organization. There lists were related via a Primary lists ID.
I had created Custom NewForms for all of the other lists and used SPGetLastItemId to populate a UID column with the ID from the Primary List.
When I did this, the ID always returned 0.

To resolve this issue I modified the SPGetLastItemId function to accept the GUID of a view on the Primay list which was configured to show all items with out folders as follows:

// Function to return the ID of the last item created on a list by a specific user. Useful for maintaining parent/child relationships
 // between list forms
 $.fn.SPServices.SPGetLastItemId = function(options) {

  var opt = $.extend({}, {
   webURL: "",    // URL of the target Web.  If not specified, the current Web is used.
   listName: "",   // The name or GUID of the list
   viewName: "",
   userAccount: "",  // The account for the user in DOMAIN\username format. If not specified, the current user is used.
   CAMLQuery: ""   // [Optional] For power users, this CAML fragment will be Anded with the default query on the relatedList
  }, options);

  var userId;
  var lastId = 0;
   operation: "GetUserInfo",
   async: false,
   userLoginName: (opt.userAccount != "") ? opt.userAccount : $().SPServices.SPGetCurrentUser(),
   completefunc: function (xData, Status) {
    $(xData.responseXML).find("User").each(function() {
     userId = $(this).attr("ID");

  // Get the list items for the user, sorted by Created, descending. If the CAMLQuery option has been specified, And it with
  // the existing Where clause
  var camlQuery = "<Query><Where>";
  if(opt.CAMLQuery.length > 0) camlQuery += "<And>";
  camlQuery += "<Eq><FieldRef Name='Author' LookupId='TRUE'/><Value Type='Integer'>" + userId + "</Value></Eq>";
  if(opt.CAMLQuery.length > 0) camlQuery += opt.CAMLQuery + "</And>";
  camlQuery += "</Where><OrderBy><FieldRef Name='Created_x0020_Date' Ascending='FALSE'/></OrderBy></Query>";

   operation: "GetListItems",
   async: false,
   webURL: opt.webURL,
   listName: opt.listName,
   viewName: opt.viewName,
   CAMLQuery: camlQuery,
   CAMLViewFields: "<ViewFields><FieldRef Name='ID'/></ViewFields>",
   CAMLRowLimit: 1,
   completefunc: function(xData, Status) {
    $(xData.responseXML).find("[nodeName=z:row]").each(function() {
     lastId = $(this).attr("ows_ID");
  return lastId;

Jul 17, 2010 at 4:58 AM

Thanks, David.

I'm not sure if you were replying in response to this thread (all the way to the bottom), but I think I need to make SPGetLastItemId work with Scope="Recursive" as an option.  Relying on a view to be present is iffy at best.