none
Update Multiple List items using SharePoint Apps via CSOM RRS feed

  • Question

  • Hi All, 

    I am looking for a code sample for updating multiple list items using Javascript and CSOM. 

    I tried this link but it threw an error.
    http://sharepoint.stackexchange.com/questions/141987/how-to-update-multiple-items-in-sharepoint-list-online-using-javascript 

    Thank you. 

    Sandy

    Tuesday, December 20, 2016 5:41 PM

Answers

  • Hi Partick, 

    The issue is solved. I was missing "<Query>" and it worked!! 

    function updateItemsNew()
    {
        var queryMainFirst = "";
        var queryFilter = "";
        var rowLimit = "";
        var queryMainLast = "";
    
        //Get All the Selected IDs
        var listItemIds  = decodeURIComponent(getQueryStringParameter("SPListItemId"));
        var delimiterlistItemIds = listItemIds.split(',');
    
        //Construct Dynamic CAML Query 
        for (var i = 0; i < delimiterlistItemIds.length ; i++) {
            queryMainFirst = "<View><Query><Where><Or>";
            queryMainMiddle = "</Or></Where></Query>"
            rowLimit = delimiterlistItemIds.length;
            queryMainLast = "</View>";
            listItemIds = decodeURIComponent(getQueryStringParameter("SPListItemId"));
            queryFilter += "<Eq><FieldRef Name='ID' /><Value Type='Counter'>" + delimiterlistItemIds[i] + "</Value></Eq>";
    
        }
        rowLimit = "<RowLimit>" + rowLimit + "</RowLimit>"
    
        var finalQuery = queryMainFirst.concat(queryFilter, queryMainMiddle, rowLimit, queryMainLast);
    
        //Get the Host Web Objects and update Workflow Tasks items. ;
        hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    
        clientContext = SP.ClientContext.get_current();
        var hostContext = new SP.AppContextSite(clientContext, hostUrl);
        var web = hostContext.get_web();
        listWF = web.get_lists().getByTitle("Workflow Tasks");
    
        //Create CAML Object
        var query = new SP.CamlQuery();
        //query.set_viewXml("<View><Where><Or><Eq><FieldRef Name='ID' /><Value Type='Counter'>10</Value></Eq></Or></Where><RowLimit>1</RowLimit></View>");
    
    
        var query = new SP.CamlQuery();
        var formattedQuery = String.format(finalQuery)
        query.set_viewXml(formattedQuery);
    
    
    
        collListItem = listWF.getItems(query);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
    
        function onQuerySucceeded(sender, args) {
            message = jQuery("#message");
           
    
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
    
                message.append(oListItem.get_item("ID")) + message.append(" , ");
    
                message.append(oListItem.get_item("Title")) + message.append(" , ");
                message.append(oListItem.get_item("Status")) + message.append(" , ");
                oListItem.set_item("Status", "Completed");
                oListItem.set_item("PercentComplete", 1);
                oListItem.set_item("WorkflowOutcome", "Approved");
                oListItem.update();
                clientContext.executeQueryAsync(on_myUpdate_Success, on_myUpdate_Failure);
            }
        }
    
        function onQueryFailed(sender, args) {
    
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    
    }
    
    
    
    function on_myUpdate_Success() {
        message = jQuery("#message");
        message.text("Updated Successfully.");
        
    }
    function on_myUpdate_Failure(sender, args) {
        var message = jQuery("#message");
        message.text("Error while updating");
        alert("Call failed. Error: " +
                args.get_message());
    }
    


    Sandy

    Monday, December 26, 2016 9:43 AM

All replies

  • Hi Sandy,

    Here you go

    http://http://sharepoint1on1.blogspot.com/2014/08/sharepoint-2013-update-list-items-with.htmlsharepoint.stackexchange.com/questions/141987/how-to-update-multiple-items-in-sharepoint-list-online-using-javascript

    https://social.msdn.microsoft.com/Forums/office/en-US/fc91b7b5-6300-4302-af93-4fc697131ec5/client-object-model-update-multiple-list-items?forum=sharepointdevelopment


    Please remember to click Mark as Answer on the answer if it helps you

    Tuesday, December 20, 2016 5:55 PM
  • Refer to the batch update option

    http://www.vrdmn.com/2013/07/batch-operations-using-javascript.html


    ---
    Rajesh
    rjesh.com| @rjesh
    You don't need to buy me a beer, if helpful just smile, vote, and mark it as answer.

    Tuesday, December 20, 2016 7:14 PM
  •  Thanks Lakshmanan and Rajesh your pointers


    @Lakshmanan: https://social.msdn.microsoft.com/Forums/office/en-US/fc91b7b5-6300-4302-af93-4fc697131ec5/client-object-model-update-multiple-list-items?forum=sharepointdevelopment was good and able to update multiple list items. But I faced one more challenge.

    Background: I am selecting multiple items (IDs 52, 53, 54) in the Tasks lists as shown:




    1. User selects the tasks.
    2. On ribbon control, clicks on “Bulk Approval
    3. Next, click on “Approve” button.
    4. A prompt for user to select the number of tasks.
    5. “Related Content” is the document library (Department) which is associated with the Nintex workflow. 

    When use clicks on Approve button I update specific list items (listItemIds) in my JavaScript function and use dynamic CAML which works well.





    and CAML Query



    When I get specific list items, when I pass those list items to onQuerySuccessed function, the list item shows selects only FIRST 3 items (51, 52, 53) and NOT the selected items which I had passed in IDs (52, 53, 54) in the list enumerator (var listItemEnumerator = collListItem.getEnumerator();) as shown:



    I want 52, 53 and 54 to be Completed status but somehow, my code is updating only first 3 items (51, 52, 53)
    I have tried “collListItem” as JavaScript global variable, but the result is still the same.

    This my entire code:

    var listItemIds; //Get the selected IDs when a user selects on SharePoint UI
    var countOfIDs;  //countof selected IDs when a user selects on SharePoint UI
    
    var clientContext;
    var hostUrl;
    var listWF;
    var collListItem;
    var message;
    
    
    jQuery(document).ready(function () {
        jQuery("#loadUpdate").click(updateItemsNew);
    
        //For Approve Reject Buttons
        jQuery("#Approve").click(Approve);
        jQuery("#Reject").click(Reject);
        
    });
    
    $(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', constructURL);
    });
    
    // This function is executed after the DOM is ready and SharePoint scripts are loaded
    // Place any code you want to run when Default.aspx is loaded in this function
    // The code creates a context object which is needed to use the SharePoint object model
    function constructURL() {
    
        hostweburl = getQueryStringParameter("SPHostUrl");
        appweburl = getQueryStringParameter("SPAppWebUrl");
        listItemIds = getQueryStringParameter("SPListItemId");
    
        hostweburl = decodeURIComponent(hostweburl);
        appweburl = decodeURIComponent(appweburl);
        listItemIds = getQueryStringParameter("SPListItemId");
    
    
        if (typeof listItemIds !== "undefined") {
            countOfIDs = listItemIds.split(',').length;
        }
    
        //loadDependentScripts();
    }
    
    
    
    function updateItemsNew()
    {
        var queryMainFirst = "";
        var queryFilter = "";
        var rowLimit = "";
        var queryMainLast = "";
    
        //Get All the Selected IDs
        var listItemIds  = decodeURIComponent(getQueryStringParameter("SPListItemId"));
        var delimiterlistItemIds = listItemIds.split(',');
    
        //Construct Dynamic CAML Query 
        for (var i = 0; i < delimiterlistItemIds.length ; i++) {
            queryMainFirst = "<View><Where><Or>";
            queryMainMiddle = "</Or></Where>"
            rowLimit = delimiterlistItemIds.length;
            queryMainLast = "</View>";
            listItemIds = decodeURIComponent(getQueryStringParameter("SPListItemId"));
            queryFilter += "<Eq><FieldRef Name='ID' /><Value Type='Counter'>" + delimiterlistItemIds[i] + "</Value></Eq>";
    
        }
        rowLimit = "<RowLimit>" + rowLimit + "</RowLimit>"
    
        var finalQuery = queryMainFirst.concat(queryFilter, queryMainMiddle, rowLimit, queryMainLast);
    
        //Get the Host Web Objects and update Workflow Tasks items. ;
        hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    
        clientContext = SP.ClientContext.get_current();
        var hostContext = new SP.AppContextSite(clientContext, hostUrl);
        var web = hostContext.get_web();
        listWF = web.get_lists().getByTitle("Workflow Tasks");
    
        //Create CAML Object
        var query = new SP.CamlQuery();
        //query.set_viewXml("<View><Where><Or><Eq><FieldRef Name='ID' /><Value Type='Counter'>10</Value></Eq></Or></Where><RowLimit>1</RowLimit></View>");
    
        var query = new SP.CamlQuery();
        var formattedQuery = String.format(finalQuery)
        query.set_viewXml(formattedQuery);
    
        collListItem = listWF.getItems(query);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
    
        function onQuerySucceeded(sender, args) {
            message = jQuery("#message");
            
    
            var listItemIds = decodeURIComponent(getQueryStringParameter("SPListItemId"));
            var delimiterlistItemIds = listItemIds.split(',');
    
    
            for (var i = 0; i < delimiterlistItemIds.length ; i++) {
                queryMainFirst = "<View><Where><Or>";
                queryMainMiddle = "</Or></Where>"
                rowLimit = delimiterlistItemIds.length;
                queryMainLast = "</View>";
                listItemIds = decodeURIComponent(getQueryStringParameter("SPListItemId"));
    
    
    
                queryFilter += "<Eq><FieldRef Name='ID' /><Value Type='Counter'>" + delimiterlistItemIds[i] + "</Value></Eq>";
    
            }
    
    
    
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
    
                message.append(oListItem.get_item("ID")) + message.append(" , ");
    
                message.append(oListItem.get_item("Title")) + message.append(" , ");
                message.append(oListItem.get_item("Status")) + message.append(" , ");
                oListItem.set_item("Status", "Completed");
                oListItem.set_item("PercentComplete", 1);
                oListItem.set_item("WorkflowOutcome", "Approved");
                oListItem.update();
                clientContext.executeQueryAsync(on_myUpdate_Success, on_myUpdate_Failure);
            }
        }
    
        function onQueryFailed(sender, args) {
    
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    
    
    }
    
    
    
    function on_myUpdate_Success() {
        message = jQuery("#message");
        message.text("Updated Successfully.");
        
    }
    function on_myUpdate_Failure(sender, args) {
        var message = jQuery("#message");
        message.text("Error while updating");
        alert("Call failed. Error: " +
                args.get_message());
    }
    
    
    
        
    
        function success2() {
            var message = jQuery("#message");
            message.text("<b>Item updated</b>");
        }
    
        function fail(sender, args) {
            alert("Call failed. Error: " +
                args.get_message());
        }
    
    function getQueryStringParameter(paramToRetrieve) {
        var params =
            document.URL.split("?")[1].split("&");
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve)
                return singleParam[1];
        }
    }
    
    
    function Approve() {
    
        alert("Are you sure you want to APPROVE these " + countOfIDs.toString() + " tasks?")
        updateItemsNew();
       
    
    
    }
    
    function Reject() {
        alert("Are you sure you want to REJECT these " + countOfIDs.toString() + " tasks?")
    
    }
    
    



    Any suggestions?

    Thank you and wish everyone merry Christmas!!

    Sandy

    Sunday, December 25, 2016 2:39 AM
  • Hi Sandy,

    What’s the value of the “message” object after all items get updated?

    It is important to ensure that the “collListItem” object holds the items with id “52,53,54”.

    Best regards,

    Patrick


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, December 26, 2016 2:06 AM
    Moderator
  • Hi Patrick, 

    "message" came from the Default.aspx page which VS2015 SharePoint App project is started a shown

      <p id="message">
                <!-- The following content will be replaced with the user name when you run the app - see App.js -->
                initializing...
            </p>

    I use to "message" to display the SharePoint list content for my troubleshooting.

    Thank you.  


    Sandy

    Monday, December 26, 2016 7:28 AM
  • Hi Partick, 

    The issue is solved. I was missing "<Query>" and it worked!! 

    function updateItemsNew()
    {
        var queryMainFirst = "";
        var queryFilter = "";
        var rowLimit = "";
        var queryMainLast = "";
    
        //Get All the Selected IDs
        var listItemIds  = decodeURIComponent(getQueryStringParameter("SPListItemId"));
        var delimiterlistItemIds = listItemIds.split(',');
    
        //Construct Dynamic CAML Query 
        for (var i = 0; i < delimiterlistItemIds.length ; i++) {
            queryMainFirst = "<View><Query><Where><Or>";
            queryMainMiddle = "</Or></Where></Query>"
            rowLimit = delimiterlistItemIds.length;
            queryMainLast = "</View>";
            listItemIds = decodeURIComponent(getQueryStringParameter("SPListItemId"));
            queryFilter += "<Eq><FieldRef Name='ID' /><Value Type='Counter'>" + delimiterlistItemIds[i] + "</Value></Eq>";
    
        }
        rowLimit = "<RowLimit>" + rowLimit + "</RowLimit>"
    
        var finalQuery = queryMainFirst.concat(queryFilter, queryMainMiddle, rowLimit, queryMainLast);
    
        //Get the Host Web Objects and update Workflow Tasks items. ;
        hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    
        clientContext = SP.ClientContext.get_current();
        var hostContext = new SP.AppContextSite(clientContext, hostUrl);
        var web = hostContext.get_web();
        listWF = web.get_lists().getByTitle("Workflow Tasks");
    
        //Create CAML Object
        var query = new SP.CamlQuery();
        //query.set_viewXml("<View><Where><Or><Eq><FieldRef Name='ID' /><Value Type='Counter'>10</Value></Eq></Or></Where><RowLimit>1</RowLimit></View>");
    
    
        var query = new SP.CamlQuery();
        var formattedQuery = String.format(finalQuery)
        query.set_viewXml(formattedQuery);
    
    
    
        collListItem = listWF.getItems(query);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
    
        function onQuerySucceeded(sender, args) {
            message = jQuery("#message");
           
    
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
    
                message.append(oListItem.get_item("ID")) + message.append(" , ");
    
                message.append(oListItem.get_item("Title")) + message.append(" , ");
                message.append(oListItem.get_item("Status")) + message.append(" , ");
                oListItem.set_item("Status", "Completed");
                oListItem.set_item("PercentComplete", 1);
                oListItem.set_item("WorkflowOutcome", "Approved");
                oListItem.update();
                clientContext.executeQueryAsync(on_myUpdate_Success, on_myUpdate_Failure);
            }
        }
    
        function onQueryFailed(sender, args) {
    
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    
    }
    
    
    
    function on_myUpdate_Success() {
        message = jQuery("#message");
        message.text("Updated Successfully.");
        
    }
    function on_myUpdate_Failure(sender, args) {
        var message = jQuery("#message");
        message.text("Error while updating");
        alert("Call failed. Error: " +
                args.get_message());
    }
    


    Sandy

    Monday, December 26, 2016 9:43 AM
  • Hi Sandy,

    Glad to hear that you solve the issue, thanks for your sharing.

    If the original issue has been resolved, it would be appreciated if you can mark the reply as answer, others who stuck with the similar issue would be easier to search for valid solutions in this forum.

    Thanks,               

    Patrick


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, December 26, 2016 1:52 PM
    Moderator