3

ListItem にさまざまな「フィールド」を挿入または更新するために、この Sharepoint (2010) Javascript (ここから適応) があります。

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());
    . . .

私の課題は、ユーザーが上記の 2 つのメソッド (upsertPostTravelListItemTravelerInfo1()) の最初の部分でデータの最初のビットを更新したい場合 (それらを挿入し、後で戻ってきて何かを変更することを決定した場合) です。

ここでも getItemById() を使用する必要があります。これが最初のエントリの場合、まだ存在していないので、次を使用します。

listId = this.oListItem.ID;

...しかし、この部分が更新されると、listId が必要になるので、次のことができます。

this.oListItem = oList.getItemById(listId);

これを行うには、正しい値を listId に割り当てるために、リストを調べて、特定の値の「レコード」が既に存在するかどうか、つまり 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 メンバー値に一致する「レコード」を検索するために、クエリのようにどのように問い合わせられますか?

アップデート

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();

つまり、「キャッチされていない TypeError: oList.getEnumerator は関数ではありません」

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() は有効な関数ですか? はいの場合、何が間違っていますか? そうでない場合、代わりに何を使用できますか?

4

2 に答える 2

1

SharePoint 2010 を使用して要求されたREST を使用した CRUD の例

RESTful サービスの利点--> すべてがHTTP経由で行われる

したがって、純粋なビアを使用できますJavaScript XMLHttpRequest

またはJQuery 経由 $.ajax

または、SharePoint 2010 Web パーツで既に使用可能であるため、この例が示すように経由します。MicrosoftAjax.js Sys.Net.WebRequest

// 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の命名規則の詳細spPageContextInfo
の詳細

于 2015-10-12T20:38:09.140 に答える