Skip to main content

Cloud

Retrieving SharePoint List Column Managed Metadata (JavaScript)

This is a quickie, but can be useful for those accessing SharePoint Managed Metadata from the Client Side.
Often when you’re pulling back data from SharePoint lists, you’ll get a full-fledged object back rather than a single field value (and yes I ran into this while working on some fancy calls in a Display Template).
2013-02-28_1544
The code itself is fairly simple, but here’s how you can go digging for an answer yourself. Go to your browser’s debugging console (F12) and inspect the JSON response from the Console for your function. Here, find the correct response for your call that contains the items from the list that you queried. From there, you can see how the objects are structured and how to access the managed metadata field properly. In the picture below, you can see where I have highlighted the metadata field that I am looking for which has a type of SP.Taxonomy.TaxonomyFieldValue.
Hope this helps you guys dig through the response from SharePoint and get you the right field values! Helpful MSDN blog to get you started with client side calls.
2013-02-28_1553
 
Now that you see the structure, the import part of your code is this (after you instantiate the enumerator to parse the items returned from the list):

   1: while (listEnumerator.moveNext()) {

   2: var keyword = listEnumerator.get_current().get_item("TileID")["Label"];

   3: }

And the complete code here:

   1: var ctx = new SP.ClientContext();

   2: var targetList = ctx.get_web().get_lists().getByTitle('ListName');

   3: var queryItems;

   4:

   5: var query = new SP.CamlQuery();

   6: query.set_viewXml("<View><Query><Where><Contains><FieldRef Name='Id'/><Value Type='Text'>FilterValue</Value></Contains></Where></Query></View>");

   7:

   8: queryItems = targetList.getItems(query);

   9: ctx.load(mandatoryItems);

  10: ctx.executeQueryAsync(onGetSucceeded, onGetFailed);

  11:

  12: function onGetSucceeded()

  13: {

  14:     var listEnumerator = queryItems.getEnumerator();

  15:

  16:     while (listEnumerator.moveNext()) {

  17:         var keywords = listEnumerator.get_current().get_item("TileID")["Label"];

  18:         alert(childItem);

  19:     }

  20: }

  21: function onGetFailed(sender, args) {

  22:   alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());

  23: }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us