Wednesday, 23 March 2016

Search a Taxonomy term in a TermSet using JSOM

Here is some code I put together to search a term within a term set. This is for scenarios when you have a large term set and need to efficiently find a term with a specific label.

Here is a link which describes the exact combinations needed to make this work (Thanks Jose!)
https://msdn.microsoft.com/en-us/library/hh626704%28v=office.12%29.aspx

In this code, I am searching for all terms which start with an "A" in a term set which contains locations from around the world:

Note: I am using JSOM here but this also works with CSOM

(function () {
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
SP.SOD.registerSod("sp.taxonomy.js", SP.Utilities.Utility.getLayoutsPageUrl("sp.taxonomy.js"));
SP.SOD.executeFunc("sp.taxonomy.js", "SP.Taxonomy.TaxonomySession", runFunc);
});
function runFunc() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Name of the Term Store from which to get the Terms.
var termStore = taxSession.getDefaultSiteCollectionTermStore();
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("7c16e180-d093-4709-8426-e7997acb4302");
var lmi = SP.Taxonomy.LabelMatchInformation.newObject(context);
//Populate the various properties
lmi.set_termLabel("a"); //search terms.
lmi.set_defaultLabelOnly(true);
lmi.set_stringMatchOption(SP.Taxonomy.StringMatchOption.startsWith);
lmi.set_resultCollectionSize(10); //terms to bring back
lmi.set_trimUnavailable(true);
var terms = termSet.getTerms(lmi);
context.load(terms, 'Include(IsRoot, Id, Name, LocalCustomProperties)');
context.executeQueryAsync(function () {
//success
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
console.log(currentTerm.get_name());
}
}, function (sender, args) {
//fail
console.log(args.get_message());
});
}
})();


Result: