I have a requirement where I have to copy list items from one list to another using REST. The requirement is that the data copied from list 'A' should be 90 days older than today. So I have written it on the click function of a button. I am able to fetch the data but while creating the items in list 'B', it goes into the error function of the create function I get the error on logging it as:
Bad Request : {"error":{"code":"-2130575257, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"A list item with ID {0} already exists."}}} though the item is not present in list 'B'.
Note: to get items I've made REST calls in batches of 5000 and pushed it into one item array, as the limit of REST
calls is 5000. There is no problem in getting items, just creating new items.
The code is given below:
var TrainingReqList = "training_requests";
var ArchiveList = "Archived_training_requests";
var TrainingReqArchiveListData = [];
function onClickArchival() {
var copyItem = {}; //array in which data fetched will be copied and this will be passed into create item function
var toCopyCount = 0;
getTRdata(); //funtion to get data in batches of 5000
for (i = 0; i < TrainingReqArchiveListData.length; i++) { //when all data is pushed into the array, conditions are invoked
var archivedate = new Date(new Date().setDate(new Date().getDate() + (-90)));
var createddate = new Date(TrainingReqArchiveListData[i]['Created']);
if (createddate <= archivedate) {
if (TrainingReqArchiveListData[i]['Status'].toString() != "New Request" && TrainingReqArchiveListData[i]['Status'].toString() != "Pending Agent Confirmation" && TrainingReqArchiveListData[i]['Status'].toString() != "Training Date Confirmed") {
var created = TrainingReqArchiveListData[i]['Created'];
var modified = TrainingReqArchiveListData[i]['Modified'];
var createduserId = TrainingReqArchiveListData[i]['AuthorId'];
var modifiedUserId = TrainingReqArchiveListData[i]['EditorId'];
toCopyCount++;
for (var propertyName in TrainingReqArchiveListData[i]) {
if (TrainingReqArchiveListData[i].hasOwnProperty(propertyName)) { //for copying the properties of list where data is fetched from
if (TrainingReqArchiveListData[i][propertyName] != null && TrainingReqArchiveListData[i][propertyName].hasOwnProperty('__deferred')) //exclude deffered objects
{
continue;
}
if (propertyName == 'GUID' || propertyName == 'ID' || propertyName == 'Id') {
continue;
}
if (propertyName == '__metadata') {
var targetItemType = "";
copyItem['__metadata'] = { 'type': "SP.Data.Archived_x005f_training_x005f_requestsListItem" };
}
}
}
//copying data into new array from the fetched data array
copyItem["Id"] = TrainingReqArchiveListData[i]["Id"];
copyItem["Status"] = TrainingReqArchiveListData[i]["Status"];
copyItem["send_x0020_webinar_x0020_link_x0"] = TrainingReqArchiveListData[i]["send_x0020_webinar_x0020_link_x0"];
copyItem["Agency_x0020_Name"] = TrainingReqArchiveListData[i]["Agency_x0020_Name"];
copyItem["Agent_x0020_Phone_x0020__x0023_"] = TrainingReqArchiveListData[i]["Agent_x0020_Phone_x0020__x0023_"];
copyItem["Agency_x0020_Producer_x0020_Code"] = TrainingReqArchiveListData[i]["Agency_x0020_Producer_x0020_Code"];
copyItem["send_x0020_webinar_x0020_link_x00"] = TrainingReqArchiveListData[i]["send_x0020_webinar_x0020_link_x00"];
copyItem["Agency_x0020_State"] = TrainingReqArchiveListData[i]["Agency_x0020_State"];
copyItem["SE_x0020_Name_x0020_Free_x0020_F"] = TrainingReqArchiveListData[i]["SE_x0020_Name_x0020_Free_x0020_F"];
copyItem["Will_x0020_SE_x0020_be_x0020_pre"] = TrainingReqArchiveListData[i]["Will_x0020_SE_x0020_be_x0020_pre"];
copyItem["Role"] = TrainingReqArchiveListData[i]["Role"];
copyItem["Training_x0020_Topic"] = TrainingReqArchiveListData[i]["Training_x0020_Topic"].results[0].toString();
copyItem["Years_x0020_of_x0020_CL_x0020_Ex"] = TrainingReqArchiveListData[i]["Years_x0020_of_x0020_CL_x0020_Ex"];
copyItem["Years_x0020_of_x0020_Travelers_x"] = TrainingReqArchiveListData[i]["Years_x0020_of_x0020_Travelers_x"];
copyItem["Scheduling_x0020_Preference"] = TrainingReqArchiveListData[i]["Scheduling_x0020_Preference"];
copyItem["Time_x0020_Zone"] = TrainingReqArchiveListData[i]["Time_x0020_Zone"];
copyItem["Requester_x0020_Note"] = TrainingReqArchiveListData[i]["Requester_x0020_Note"];
copyItem["Date_x0020_Selection"] = TrainingReqArchiveListData[i]["Date_x0020_Selection"];
copyItem["Time_x0020_Selection"] = TrainingReqArchiveListData[i]["Time_x0020_Selection"];
copyItem["Date_x002f_Time"] = TrainingReqArchiveListData[i]["Date_x002f_Time"];
copyItem["Submitted_x0020_ById"] = TrainingReqArchiveListData[i]["Submitted_x0020_ById"];
copyItem["AAE_x0020_AssignedId"] = TrainingReqArchiveListData[i]["AAE_x0020_AssignedId"];
copyItem["Admin_x0020_Notes"] = TrainingReqArchiveListData[i]["Admin_x0020_Notes"];
copyItem["Region"] = TrainingReqArchiveListData[i]["Region"];
copyItem["Training_x0020_Type"] = TrainingReqArchiveListData[i]["Training_x0020_Type"];
copyItem["New_x0020_Appointment"] = TrainingReqArchiveListData[i]["New_x0020_Appointment"];
copyItem["Scheduled_x0020_Training"] = TrainingReqArchiveListData[i]["Scheduled_x0020_Training"];
copyItem["Breakout_x0020_Session_x0020_Hel"] = TrainingReqArchiveListData[i]["Breakout_x0020_Session_x0020_Hel"];
copyItem["OData__x0023__x0020_B_x002f_O_x0020_Pa"] = TrainingReqArchiveListData[i]["OData__x0023__x0020_B_x002f_O_x0020_Pa"];
copyItem["OData__x0023__x0020_of_x0020_Participa"] = TrainingReqArchiveListData[i]["OData__x0023__x0020_of_x0020_Participa"];
copyItem["OData__x0023__x0020_New_x0020_Users"] = TrainingReqArchiveListData[i]["OData__x0023__x0020_New_x0020_Users"];
copyItem["secondary_x0020_training"] = TrainingReqArchiveListData[i]["secondary_x0020_training"];
copyItem["confirmed_x0020_producer_x0020_c"] = TrainingReqArchiveListData[i]["confirmed_x0020_producer_x0020_c"];
copyItem["Primary_x0020_TrainingTopic"] = TrainingReqArchiveListData[i]["Primary_x0020_TrainingTopic"];
copyItem["Additional_x0020_attendees"] = TrainingReqArchiveListData[i]["Additional_x0020_attendees"];
copyItem["Record_x0020_Status"] = TrainingReqArchiveListData[i]["Record_x0020_Status"];
copyItem["RequestID"] = TrainingReqArchiveListData[i]["RequestID"];
copyItem["Created"] = TrainingReqArchiveListData[i]["Created"];
copyItem["Notes"] = TrainingReqArchiveListData[i]["Notes"];
copyItem["RequestSource"] = TrainingReqArchiveListData[i]["RequestSource"];
copyItem["IfMulti"] = TrainingReqArchiveListData[i]["IfMulti"];
copyItem["Modified"] = TrainingReqArchiveListData[i]["Modified"];
copyItem["AAE_x0020_Assigned"] = TrainingReqArchiveListData[i]["AAE_x0020_Assigned"];
copyItem["Submitted_x0020_By"] = TrainingReqArchiveListData[i]["Submitted_x0020_By"];
AddListItem(ArchiveList, copyItem); //function call to create new items in Archive list
}
}
}
console.log('Total items in ' + TrainingReqList + ': ' + TrainingReqArchiveListData.length);
console.log('Total number of items to be archived to ' + ArchiveList + ': ' + toCopyCount);
}
To get data, I've used the following functions
function getTRdata() {
var checkTopIdFilter = "?$select = Id&$orderby=Id asc&$top=1";
var callTrainingReqListCheckTopId = GetListItems(TrainingReqList, null, checkTopIdFilter);
$.when(callTrainingReqListCheckTopId).then(function (tData) {
if (tData.d.results.length != 0) {
var startId1 = tData.d.results[0].Id;
var endId1 = startId1 + 4999;
var startId2 = endId1 + 1;
var endId2 = startId2 + 4999;
var startId3 = endId2 + 1;
var endId3 = startId3 + 4999;
var startId4 = endId3 + 1;
var endId4 = startId4 + 4999;
var trFilter1 = "?$filter=((Id ge " + startId1 + ") and (Id le " + endId1 + "))&$top=5000";
var trFilter2 = "?$filter=((Id ge " + startId2 + ") and (Id le " + endId2 + "))&$top=5000";
var trFilter3 = "?$filter=((Id ge " + startId3 + ") and (Id le " + endId3 + "))&$top=5000";
var callTrainingReqList1 = GetListItems(TrainingReqList, null, trFilter1); //rest call to get data of first 5000
var callTrainingReqList2 = GetListItems(TrainingReqList, null, trFilter2); //rest call to get data of next 5000
var callTrainingReqList3 = GetListItems(TrainingReqList, null, trFilter3); //rest call to get data of next 5000
$.when(callTrainingReqList1, callTrainingReqList2, callTrainingReqList3).then(function (trData1, trData2, trData3) {
for (var i = 0; i < trData1[0].d.results.length; i++) {
var confDateTime, createdDateTime, modifiedDateTime;
if (trData1[0].d.results[i].Date_x002f_Time != null || trData1[0].d.results[i].Date_x002f_Time != undefined) confDateTime = new Date(trData1[0].d.results[i].Date_x002f_Time).format("yyyy-MM-ddTHH:mm:ssZ");
else confDateTime = trData1[0].d.results[i].Date_x002f_Time;
if (trData1[0].d.results[i].Created != null || trData1[0].d.results[i].Created != undefined) createdDateTime = new Date(trData1[0].d.results[i].Created).format("yyyy-MM-ddTHH:mm:ssZ");
else createdDateTime = trData1[0].d.results[i].Created;
if (trData1[0].d.results[i].Modified != null || trData1[0].d.results[i].Modified != undefined) modifiedDateTime = new Date(trData1[0].d.results[i].Modified).format("yyyy-MM-ddTHH:mm:ssZ")
else modifiedDateTime = trData1[0].d.results[i].Modified;
TrainingReqArchiveListData.push(trData1[0].d.results[i]); //pushing first 5000 data into array
}
for (var i = 0; i < trData2[0].d.results.length; i++) {
var confDateTime, createdDateTime, modifiedDateTime;
if (trData2[0].d.results[i].Date_x002f_Time != null || trData2[0].d.results[i].Date_x002f_Time != undefined) confDateTime = new Date(trData2[0].d.results[i].Date_x002f_Time).format("yyyy-MM-ddTHH:mm:ssZ");
else confDateTime = trData2[0].d.results[i].Date_x002f_Time;
if (trData2[0].d.results[i].Created != null || trData2[0].d.results[i].Created != undefined) createdDateTime = new Date(trData2[0].d.results[i].Created).format("yyyy-MM-ddTHH:mm:ssZ");
else createdDateTime = trData2[0].d.results[i].Created;
if (trData2[0].d.results[i].Modified != null || trData2[0].d.results[i].Modified != undefined) modifiedDateTime = new Date(trData2[0].d.results[i].Modified).format("yyyy-MM-ddTHH:mm:ssZ")
else modifiedDateTime = trData2[0].d.results[i].Modified;
TrainingReqArchiveListData.push(trData2[0].d.results[i]); //pushing next 5000 data into array
}
for (var i = 0; i < trData3[0].d.results.length; i++) {
var confDateTime, createdDateTime, modifiedDateTime;
if (trData3[0].d.results[i].Date_x002f_Time != null || trData3[0].d.results[i].Date_x002f_Time != undefined) confDateTime = new Date(trData3[0].d.results[i].Date_x002f_Time).format("yyyy-MM-ddTHH:mm:ssZ");
else confDateTime = trData3[0].d.results[i].Date_x002f_Time;
if (trData3[0].d.results[i].Created != null || trData3[0].d.results[i].Created != undefined) createdDateTime = new Date(trData3[0].d.results[i].Created).format("yyyy-MM-ddTHH:mm:ssZ");
else createdDateTime = trData3[0].d.results[i].Created;
if (trData3[0].d.results[i].Modified != null || trData3[0].d.results[i].Modified != undefined) modifiedDateTime = new Date(trData3[0].d.results[i].Modified).format("yyyy-MM-ddTHH:mm:ssZ")
else modifiedDateTime = trData3[0].d.results[i].Modified;
TrainingReqArchiveListData.push(trData3[0].d.results[i]); //pushing next 5000 data into array
}
});
}
});
}
function GetListItems(listName, id, filter) {
if (id != null) { var siteURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items/getbyid('" + id + "')" + filter; }
else { var siteURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items" + filter; }
return $.ajax({
url: siteURL,
async: false,
method: "GET",
headers: { "Accept": "application/json;odata=verbose" }
});
}
To write data into new list:
function AddListItem(listname, ArchiveMetadata) { //function to create new items in Archive list (ArchiveMetadata is passed as copyItem)
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items",
type: "POST",
data: JSON.stringify(ArchiveMetadata),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
success: function (data) {
console.log("Item Id: " + ArchiveMetadata.Id + " copied");
},
error: function (data) {
console.log(data.statusText + " : " + data.responseText);
console.log("Item Id: " + ArchiveMetadata.Id + " not copied");
}
});
}