5

I am developing a custom ribbon action as Sharepoint hosted app, where the user can select any number of list items and click on the action. On click of the ribbon action, the app redirects to the app landing page where I can fetch the selected item IDs. Now I need to retrieve the respective list items. One of the crude option is to loop the IDs and fetch the list items which I want to avoid.

I tried the batch processing in Javascript object model - use getitembyid method on each item ID, put the result into an array and call the

context.load(array);

This does not seem to work. I thought of creating a camlquery XML in loop for all list items and execute the query once !!

Any suggestions for better approach ?

9

Since you haven't specified what error occurs, below is demonstrated how to load multiple list items by their ids:

var listTitle = 'Tasks'; //list title
var ids = [1,2,3];  //item ids

var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var result = []; //for storing items 
ids.forEach(function(id){
    var item = list.getItemById(id);
    ctx.load(item);
    result.push(item);
});
ctx.executeQueryAsync(
  function() {
     result.forEach(function(item){
        console.log(item.get_item('Title')); 
     });
  },
  function(sender,args){
     console.log(args.get_message());
  }
); 
  • 1
    Ah ! I was trying to load the array of items ! This worked. Thanks. – Vipul Kelkar May 31 '15 at 11:27
2

You should be able to do it via CAML.

The query should be somewhat like this:

<Where>
  <Or>
     <Eq>
        <FieldRef Name='ID' />
        <Value Type='Number'>{FirstID}</Value>
     </Eq>
     <Eq>
        <FieldRef Name='ID' />
        <Value Type='Number'>{SecondID}</Value>
     </Eq>
  </Or>
</Where>

Here's a complete example:

var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('YourListName');
var ids = [1, 2, 3]; 

//create caml
var query = new SP.CamlQuery();
var q = "<View><Query><Where><Or>";
ids.forEach(function (id) {
    q += "<Eq><FieldRef Name='ID' /><Value Type='Number'>" + id + "</Value></Eq>";
});
q += "</Or></Where></Query></View>";

query.set_viewXml(q);
var results = list.getItems(query);

ctx.load(results, 'Include(Id, Title)');
ctx.executeQueryAsync(
    function () {
        var listEnumerator = results.getEnumerator();
        while (listEnumerator.moveNext()) {
            var currentItem = listEnumerator.get_current();
        }
    },
    function (sender, args) {
        //error
    }
);

Here's a similar approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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