4

Is it possible to create multiple list items with one function in JavaScript / ECMAScript? I know that a single item can be created with the code below, but would like to know if it is possible to use a loop or something to create multiple list items rather than calling the function over and over.

var siteUrl = '/sites/MySiteCollection';

function createListItem() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');

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

    oListItem.set_item('Title', 'My New Item!');
    oListItem.set_item('Body', 'Hello World!');

    oListItem.update();

    clientContext.load(oListItem);

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

function onQuerySucceeded() {
    alert('Item created: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

1 Answer 1

4

Since CSOM is request batching process, you could prepare multiple ListItem objects and then create all of them with a single query.

The code below demonstrates how create multiple tasks:

function createListItems(listTitle,itemsProperties,OnItemsAdded,OnItemsError)
{
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(listTitle);

    var items = [];
    $.each(itemsProperties, function (i, itemProperties) {

       var itemCreateInfo = new SP.ListItemCreationInformation();
       var listItem = list.addItem(itemCreateInfo);
       for(var propName in itemProperties) {
          listItem.set_item(propName, itemProperties[propName]) 
       }
       listItem.update();
       context.load(listItem);
       items.push(listItem);

    });

    context.executeQueryAsync(
        function() {
          OnItemsAdded(items);           
        },
        OnItemsError
    );
}



//Usage
var tasksProperties = [{'Title':'Approval','Body':'Planned Purchase Orders Approval'},
                       {'Title':'Aggrement','Body':'Contract Purchase Agreements Approval'}];


createListItems('Tasks',tasksProperties,
     function(items){
           console.log('Tasks have been created successfully');
     },
     function(sender,args){
          console.log('Error occured while creating tasks:' + args.get_message());
     }
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.