Created
September 11, 2016 10:25
-
-
Save dev-kperera/4141b6b1ab3316e31e1fc80ca1d9fa79 to your computer and use it in GitHub Desktop.
Get/ Resolve Term ID for Term Value in SharePoint.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Resolve Term ID for the Term Value | |
function getTermIdForTermValue(siteUri, listName, fieldName, termValue) { | |
//Define | |
var deferred = $q.defer() | |
, termId; | |
var clientContext = new SP.ClientContext(siteUrl); | |
var list = clientContext.get_web().get_lists().getByTitle(listName); | |
//Tx field | |
var field = list.get_fields().getByInternalNameOrTitle(fieldName); | |
var txField = clientContext.castTo(field, SP.Taxonomy.TaxonomyField); | |
//load context | |
clientContext.load(field); | |
clientContext.load(txField); | |
// //excute async of context | |
clientContext.executeQueryAsync( | |
//Success on Async | |
Function.createDelegate(this | |
, function () { | |
//Getting term set of the field | |
var termSetId = txField.get_termSetId().toString(); | |
var tSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext); | |
var ts = tSession.getDefaultSiteCollectionTermStore(); | |
var tset = ts.getTermSet(termSetId); | |
//Define term label to match | |
var lmi = new SP.Taxonomy.LabelMatchInformation(clientContext); | |
lmi.set_lcid(1033); | |
lmi.set_trimUnavailable(true); | |
lmi.set_termLabel(termValue); | |
var termMatches = tset.getTerms(lmi); | |
//context loading with taxanomy values | |
clientContext.load(tSession); | |
clientContext.load(ts); | |
clientContext.load(tset); | |
clientContext.load(termMatches); | |
clientContext.executeQueryAsync( | |
function () { | |
if (termMatches && termMatches.get_count() > 0) { | |
termId = termMatches.get_item(0).get_id().toString(); | |
console.log("Resolved Term Id for Term " + termValue, termId); | |
deferred.resolve(termId); | |
} | |
else { | |
console.log("No IDs to resolved for Term " + termValue); | |
deferred.resolve(null); | |
} | |
} | |
, function (sender, args) { | |
console.log("Error on resolving term ID", args); | |
deferred.reject(null); | |
}); | |
} | |
, function (sender, args) { | |
console.log(args.get_message() + '\n' + args.get_stackTrace()); | |
}) | |
//Failed on Async | |
, Function.createDelegate(this, function (err) { | |
console.error(err.get_message()); | |
}) | |
); | |
return deferred.promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment