createListItem with SP.ClientContext in for each loop
-
01-01-2021 - |
Domanda
we use a custom aspx page in SharePoint 2013 to create list items in a for each loop via sp.js - works fine!
function PushValuesToList(results) {
results.forEach(function(entry) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createListItem(entry.Bestellmenge)); //makes sure sp.js is loaded and then calls createListItem method
});
}
function createListItem(Menge) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('AnforderungenSAS');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('BenMenge', Menge);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
console.log('Item created: ' + oListItem.get_id());
}
function onQueryFailed(sender, args) {
//error
}
Problem is that when I create three items in via the loop it returns the following ids:
Item created: -1
Item created: 235
Item created: 235
Instead of the right ids from the list. What am I doing wrong?
Soluzione
Code seems fine,something wrong in the way loop is called.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createListItem());
function createListItem() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('AnforderungenSAS');
for(count = 0; count < entry.Bestellmenge; count++){
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('BenMenge', Menge);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange