Friday, June 1, 2018

CSOM CamlQuery Example - Returning list items that fall within a specified date range

Since CamlQuery isn't very intuitive or easy to work with, I thought I'd put together a serious of posts that display some examples that you can use in order to make it work better for you.

In this particular example, I'm connecting to a SharePoint list and performing the following activities:

  1. Filtering the list items that were created within a specified date range while, also, ignoring the time values.  NOTE:  If you need to include the time values, simply change the IncludeTimeValue attribute from FALSE to TRUE.
  2. Ordering the list so that it returns the most recently created items first and older items last
So that you can focus on the actual CamlQuery structure, I've greatly simplified the code as follows:

var selectedMinDate = '2018-1-1';
var selectedMaxDate = '2018-1-31';
var camlQueryText = "<View><Query><Where><And><Geq><FieldRef Name=\'Created\' /><Value Type=\'DateTime\' IncludeTimeValue=\'FALSE\' >"
+ selectedMinDate + "</Value></Geq><Lt><FieldRef Name=\'Created\' /><Value Type=\'DateTime\' IncludeTimeValue=\'FALSE\' >"
+ selectedMaxDate + "</Value></Lt></And></Where><OrderBy><FieldRef Name=\'Created\' Ascending=\'False\' /></OrderBy></Query></View>";
var ctx = new SP.ClientContext.get_current();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(camlQueryText);
this.items = ctx.get_web().get_lists().getByTitle('NameOfList').getItems(camlQuery);
ctx.load(items);
ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

function onQuerySucceeded(sender, args) {
     while (listItemEnumerator.moveNext()) {
          var oListItem = listItemEnumerator.get_current();
          var itemInfo = oListItem.get_item('Title') + " - " + oListItem.get_item('Created');
          alert(itemInfo);
     }
}
function onQueryFailed(sender, args) {
     alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.