如何根据几个已知值确定 Sharepoint ListItem 是否存在?

How can I determine if a Sharepoint ListItem exists based on a couple of known values?

我有这个 Sharepoint (2010) Javascript(改编自 here)用于在 ListItem 中插入或更新各种 "fields":

var listId;

. . .

function upsertPostTravelListItemTravelerInfo1() {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

  var itemCreateInfo = new SP.ListItemCreationInformation();
  this.oListItem = oList.addItem(itemCreateInfo);

  listId = this.oListItem.ID;
  oListItem.set_item('ptli_formFilledOut', new Date());
  oListItem.set_item('ptli_TravelersName', $('travelername').val());
    . . .

  oListItem.update();

  clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

在上面的代码中,第一个"upsert"存储了"listId";随后写入列表(它将被逐个写入,以防用户停止或某些东西阻止了他们,他们稍后又回来了)使用 getItemById() 方法获取之前开始的 ListItem:

function upsertPostTravelListItemTravelerInfo2() {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');
  this.oListItem = oList.getItemById(listId);

  oListItem.set_item('ptli_tripNumber', $('tripnumber').val());
    . . .

我的挑战是用户想要在上面显示的两种方法中的第一种中更新数据的第一位(他们插入这些数据,然后稍后返回并决定更改某些内容)(upsertPostTravelListItemTravelerInfo1() ).

我在这里也需要使用 getItemById()。当这是第一个条目时,它还不存在,我使用:

listId = this.oListItem.ID;

...但是当这部分正在更新时,将需要 listId 以便我可以:

this.oListItem = oList.getItemById(listId);

为此 - 将正确的值分配给 listId - 我需要查询列表以查看某些值的 "record" 是否已经存在,因此已经有一个 listId;伪代码:

listId = //a "record" with a username value of "<userName>" and a payeeName of "<payeeName>" with a "Completed" value of "false")
if (listId == null) {
      var itemCreateInfo = new SP.ListItemCreationInformation();
      this.oListItem = oList.addItem(itemCreateInfo);
      listId = this.oListItem.ID;

} else {
      this.oListItem = oList.getItemById(listId);
}

我的问题是:我需要用什么来替换伪代码? Sharepoint 2010 ListItem 是如何被询问的,类似查询,以找到特定 ListItem 成员值的匹配 "record"?

更新

根据 crclayton 的第一个想法,我是这样想的:

function upsertPostTravelListItemTravelerInfo1() {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

  this.website = context.get_web();
  this.currentUser = website.get_currentUser();

  var itemCreateInfo = new SP.ListItemCreationInformation();
  this.oListItem = oList.addItem(itemCreateInfo);

  var travelersEmail = $('traveleremail').val());

  /* If this is an update, the call to getListItemID() will return a val; otherwise (an insert), get from newly instantiated ListItem.  */
  listId = getListItemID(currentUser, travelersEmail);
  if (listId === '') {
    listId = this.oListItem.ID; 
  }

  oListItem.set_item('ptli_formFilledOut', new Date());
  oListItem.set_item('ptli_TravelersName', $('travelername').val());
  oListItem.set_item('ptli_TravelersEmail', travelersEmail);
  . . .
}

function getListItemID(username, payeename) {
  var arrayListEnum = oList.getEnumerator();

  while (arrayListEnum.moveNext()) {
     var listItem = arrayListEnum.get_current();

     if(listItem.get_item("ptli_formPreparedBy") === username &&
        listItem.get_item("ptli_TravelersEmail") === payeename &&
        listItem.get_item("ptli_formCompleted") == false) {

         return listItem.get_id();    
     }
   }
   return '';
}

...可能是门票。

更新 2

根据回答,我在这一行收到一条错误信息:

var arrayListEnum = oList.getEnumerator();

即"Uncaught TypeError: oList.getEnumerator is not a function"

是不是没有名为 getEnumerator() 的函数,或者...???

更新 3

我仍然得到,"Uncaught TypeError: oList.getEnumerator is not a function" 这个(修改过的)代码:

function getListItemID(username, payeename, oList) {
    var clientContext = new SP.ClientContext.get_current();
    var listItems = oList.getItems("");
    clientContext.load(listItems);
    clientContext.executeQueryAsync(function () {

        var arrayListEnum = oList.getEnumerator();

        while (arrayListEnum.moveNext()) {
            var listItem = arrayListEnum.get_current();

            if (listItem.get_item("userName") === "<userName>" &&
        listItem.get_item("payeeName") === "<payeeName>" &&
        listItem.get_item("Completed") == false) {

                return listItem.get_id();
            }
        }
        return '';
    });
}

我是这样称呼它的:

function upsertPostTravelListItemTravelerInfo1() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

    this.website = clientContext.get_web();
    currentUser = website.get_currentUser();

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);

    var travelersEmail = $('traveleremail').val();

    /* If this is an update, the call to getListItemID() will return a val; otherwise (an insert), get from newly instantiated ListItem.  */
    listId = getListItemID(currentUser, travelersEmail, oList);
    if (listId === '') {
        listId = this.oListItem.ID;
    }

那么 getEnumerator() 是不是一个有效的函数?如果是,我做错了什么?如果没有,我可以用什么代替它?

它可能不像您想要的那样像查询,但是像这样的东西呢:

 var clientContext = new SP.ClientContext.get_current();
 var listItems = oList.getItems("");
 clientContext.load(listItems);
 clientContext.executeQueryAsync(function(){

     var arrayListEnum = listItems.getEnumerator();

     while (arrayListEnum.moveNext()) {
         var listItem = arrayListEnum.get_current();

         if(listItem.get_item("userName") === "<userName>" &&
            listItem.get_item("payeeName") === "<payeeName>" &&
            listItem.get_item("Completed") == false) {

                return listItem.get_id();    
         }
     }
 });

或者您可以像这样使用 CAML 查询:

 var query = new SP.CamlQuery();
 query.set_viewXml("<View><Query><Where><Contains><FieldRef Name='userName'/>" +
                    "<Value Type='Text'>userName</Value></Contains></Where></Query>" + 
                    "</View>");
 listItems = oList.getItems(query);

 clientContext.load(listItems);
 clientContext.executeQueryAsync(onQuerySucceeded, function(){Alert("not found");});

 ...

 function onQuerySucceeded() {
    var listEnumerator = listItems.getEnumerator();
    while (listEnumerator.moveNext()) {
        console.log(listEnumerator.get_current().get_id());
    }  
 }

使用 REST 的 CRUD 示例
根据要求使用 SharePoint 2010

RESTful 服务的美妙之处 --> 一切都发生在 HTTP

因此,您可以使用纯 JavaScript via XMLHttpRequest

JQuery 通过 $.ajax

MicrosoftAjax.js 通过 Sys.Net.WebRequest
如本示例所示,因为它已在 SharePoint 2010 Web 部件中可用

// test rest on SharePoint 2010
testREST();

function testREST() {
  /*
  **  List name: Test List (collapse spaces)
  **  Find list item - Set query in url --> ListName?$filter=
  **  Or access by list item id --> ListName(id)
  */
  invokeRequest({
    // make GET request with url query
    // REST also allows expansion of lookup fields
    //  --  here, i check `ModifiedBy` for `[Me]`
    'url': "TestList?$filter=" +
           "TextColumn eq 'row 1' and " +
           "NumberColumn lt 3 and " +
           "ModifiedById eq " + _spPageContextInfo.userId,

    // GET request
    'verb': "GET",

    // not needed for GET requests
    'body': null,
    'match': null,
    'method': null,

    // on complete
    'success': function (jsonObj) {
      // check the results of our query, returned in array: jsonObj.d.results
      // fyi -- if id used -- ListName(id) -- no array, one object: jsonObj.d
      if (jsonObj.d.results.length === 0) {
        // nothing found, insert new item
        insertItem();
      } else {
        // check field for _first_ item returned -- NumberColumn
        if (jsonObj.d.results[0].NumberColumn < 2) {
          // update if less than 2
          updateItem(jsonObj.d.results[0]);
        } else {
          // delete if greater than or equal to 2
          deleteItem(jsonObj.d.results[0]);
        }
      }
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

function insertItem() {
  /*
  **  List name: Test List
  **  Insert list item
  */
  invokeRequest({
    // make POST request for insert
    'url': "TestList",
    'verb': "POST",

    // use MicrosoftAjax.js to serialize our new list item
    'body': Sys.Serialization.JavaScriptSerializer.serialize({
      // set a key: value according to the column names in the list
      Title: "TEST",
      TextColumn: "row 1",
      EmployeeId: _spPageContextInfo.userId,
      NumberColumn: 1,
      DateColumn: new Date()
    }),

    // new item -- match & method not needed
    'match': null,
    'method': null,

    // on complete
    'success': function (jsonObj) {
      // print new list item to console
      var s = '';
      for (var key in jsonObj.d) {
        if (jsonObj.d.hasOwnProperty(key)) {
          s += key + ' = ' + jsonObj.d[key] + '\n';
        }
      }
      console.log('new list item\n' + s);
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

function updateItem(listItem) {
  /*
  **  List name: Test List
  **  Update list item
  */
  invokeRequest({
    // make POST request for insert -- set ID on url
    'url': "TestList(" + listItem.Id + ")",
    'verb': "POST",

    // serialize our updates -- literal w/ field name keys
    'body': Sys.Serialization.JavaScriptSerializer.serialize({
      Title: listItem.TextColumn + " test",
      NumberColumn: Number(listItem.NumberColumn) + 1
    }),

    // send the -- etag match -- for our update
    'match': listItem.__metadata.etag,

    // MERGE allows updates to one or more fields
    'method': "MERGE",

    // on complete
    'success': function (jsonObj) {
      // print request body -- _updated fields_ -- to console
      var newFields = Sys.Serialization.JavaScriptSerializer.deserialize(jsonObj.body);
      var s = '';
      for (var key in newFields) {
        if (newFields.hasOwnProperty(key)) {
          s += key + ' = ' + newFields[key] + '\n';
        }
      }
      console.log('updated list item\n' + s);
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

function deleteItem(listItem) {
  /*
  **  List name: Test List
  **  Delete list item
  */
  invokeRequest({
    // make POST request for delete -- set ID on url
    'url': "TestList(" + listItem.Id + ")",
    'verb': "POST",

    // no body needed for delete
    'body': null,

    // send the match for delete method
    'match': listItem.__metadata.etag,
    'method': "DELETE",

    // on complete
    'success': function (jsonObj) {
      // print request url for delete request
      console.log('deleted list item request\n' + jsonObj.url);
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

// invoke web request using [MicrosoftAjax.js](https://msdn.microsoft.com/en-us/library/vstudio/bb397536(v=vs.100).aspx)
function invokeRequest(requestObj) {
  // new web request
  var webRequest = new Sys.Net.WebRequest();

  // set request headers
  webRequest.get_headers()['Cache-Control'] = 'no-cache';
  webRequest.get_headers()['Accept'] = 'application/json';
  webRequest.get_headers()['Content-Type'] = 'application/json';

  // set etag match
  if (requestObj.match !== null) {
    webRequest.get_headers()['If-Match'] = requestObj.match;
  }

  // set method
  if (requestObj.method !== null) {
    webRequest.get_headers()['X-HTTP-Method'] = requestObj.method;
  }

  // set request verb
  webRequest.set_httpVerb(requestObj.verb);

  // set request body
  if (requestObj.body !== null) {
    webRequest.set_body(requestObj.body);
  }

  // set request url
  webRequest.set_url(
    _spPageContextInfo.webServerRelativeUrl + '/_vti_bin/ListData.svc/' + requestObj.url
  );

  // set user context
  webRequest.set_userContext(requestObj);

  // set completed callback and invoke request
  webRequest.add_completed(serviceComplete);
  webRequest.invoke();
}

// process web request
function serviceComplete(executor, args) {
  // check response
  if (executor.get_responseAvailable()) {
    // check status
    switch (executor.get_statusCode()) {
      case 200:   // OK
      case 201:   // Created
        // raise success callback - pass list item
        executor.get_webRequest().get_userContext().success(
          executor.get_object()
        );
        break;

      case 202:   // Accepted
      case 203:   // Non auth info
      case 204:   // No content
      case 205:   // Reset
      case 206:   // Partial
      case 1223:  // No content (SP)
        // raise success callback - pass original request object
        executor.get_webRequest().get_userContext().success(
          executor.get_webRequest().get_userContext()
        );
        break;

      // Error
      default:
        // raise fail callback - pass status
        executor.get_webRequest().get_userContext().fail(
          executor.get_statusCode(),
          executor.get_statusText()
        );
    }
  } else {
    // check timeout
    if (executor.get_timedOut()) {
      executor.get_webRequest().get_userContext().fail(408,'Request Timeout');
    } else {
      // check abort
      if (executor.get_aborted()) {
        executor.get_webRequest().get_userContext().fail(800,'Request Aborted');
      } else {
        executor.get_webRequest().get_userContext().fail(801,'Unknown Error');
      }
    }
  }
}

有关 SharePoint 2010 中 naming conventions 的更多信息
更多关于 spPageContextInfo