SharePoint 2013 JavaScript API – SP.Taxonomy.LabelMatchInformation

I’ve been working with the SharePoint 2013 JavaScript recently and had cause to want to fetch the Id of a Term within the Term Store using the Taxonomy namespace.

Problem was, the documentation about this particular aspect of the JavaScript API is less than comprehensive to put it politely. In fact it’s pretty mysterious. However I managed to glean that in order to select a specific set of terms relating to a specific label you need to use the SP.Taxonomy.TaxonomySession getTerms() method and pass the method a single parameter of type SP.Taxonomy.LabelMatchInformation.

This is where my problems started.  The documentation says to create an instance of this type you need to pass in a parameter ‘a’ to the constructor.  No information on type of parameter at all.  So I tried simply putting in a string which was the label for my term. Nope. Null? Nope. Zero? Nope.  OK … how about the client context? Bingo!  Yep it’s the client context.  Except that doesn’t actually seem to work when you pass it into the getTerms() method, it doesn’t error, but neither does it actually allow you to enumerate through the returned terms.

OK, back to the drawing board. What about that method called newObject?  So I tried that also with the Client Context and double Bingo … yep created an instance of the SP.Taxonomy.LabelMatchInformation type and it created the enumerator for the returned terms in the call-back function correctly.

So if you want to fetch just a few terms from the term store, don’t bother using the constructor for the SP.Taxonomy.LabelMatchInformation type, use the newObject() method and pass in the Client Context and you’ll be fine….

Almost.

What I also found was that unless you fully populate the SP.Taxonomy.LabelMatchInformation with initial values, it also gives you problems, despite the fact that the documentation says there are default settings.  So here’s a snippet of code to successfully create  a call to the terms store to fetch a specific term:

// Get the client context
var context = SP.ClientContext.get_current();

// Create the taxonomy session passing in the client context
var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);

// Create new instance of LabelMatchInformation
var lmi = SP.Taxonomy.LabelMatchInformation.newObject(context);

//Populate the various properties
lmi.set_termLabel('MyTerm');
lmi.set_defaultLabelOnly(true);
lmi.set_stringMatchOption(SP.Taxonomy.StringMatchOption.exactMatch);
lmi.set_lcid(_spPageContextInfo.currentLanguage);
lmi.set_resultCollectionSize(1);
lmi.set_trimDeprecated(true);
lmi.set_trimUnavailable(true);
terms = taxonomySession.getTerms(lmi);
context.load(terms);
context.executeQueryAsync(successcallback, failurecallback);

function successcallback(sender, args) 
{
    //Do something with result.
}
function failurecallback(sender, args) 
{
    //Show some error message.
}

Cheers

Dave Mc