Monday, June 5, 2017

Perform CAML queries with managed metadata fields to Sharepoint lists via javascript object model

In this post I will show how to perform CAML queries which contain conditions with managed metadata (taxonomy) fields via javascript object model (JSOM). Suppose that we have custom list with 2 fields:

  1. Location – managed metadata
  2. Path – single line text which contains url for specific location

We need to query this list using location value and get path for this specific location. Here is the javascript code which can be used for that:

   1: SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
   2:     try {
   3:         if (typeof (location) == "undefined" || location == null ||
   4:             location == "") {
   5:             return;
   6:         }
   7:  
   8:         var ctx = new SP.ClientContext("http://example.com");
   9:         var list = ctx.get_web().get_lists().getByTitle("Locations");
  10:         var query = new SP.CamlQuery();
  11:         query.set_viewXml(
  12:             '<View>' +
  13:                 '<Query>' +
  14:                     '<Where>' +
  15:                         '<Contains>' +
  16:                           '<FieldRef Name=\'Location\'/>' +
  17:                           '<Value Type=\'Text\'>' + location + '</Value>' +
  18:                         '</Contains>' +
  19:                     '</Where>' +
  20:                 '</Query>' +
  21:                 '<RowLimit>1</RowLimit>' +
  22:             '</View>');
  23:  
  24:         var items = list.getItems(query);
  25:         ctx.load(items, 'Include(Path)');
  26:         ctx.executeQueryAsync(
  27:             Function.createDelegate(this, function (sender, args) {
  28:                 var path = "";
  29:                 var enumerator = items.getEnumerator();
  30:                 while (enumerator.moveNext()) {
  31:                     var item = enumerator.get_current();
  32:                     path = item.get_item("Path").get_url();
  33:                     break;
  34:                 }
  35:  
  36:                 console.log("Path: " + path);
  37:             }),
  38:             Function.createDelegate(this, function (sender, args) {
  39:                 console.log(args.get_message());
  40:             }));
  41:  
  42:     } catch (ex) {
  43:         console.log(ex.message);
  44:     }
  45: });

Code is self-descriptive so I won’t detailed explain what it does. The only moment to notice is that in order to get list item by taxonomy value in Location field we use Contains operator and pass term label to the query (lines 12-22). After that we just iterate through returned items (in this example we set RowLimit to 1, but in your scenarios you can of course get many items) and read Path field value. In order to be able to access Path field we included it to result set (line 25).

No comments:

Post a Comment