function
SetManagedMetaDataField(listName,
itemID,
fieldName,
term) {
appweburl = decodeURIComponent(getQueryStringParameter(
'SPAppWebUrl'
));
hostweburl = decodeURIComponent(getQueryStringParameter(
'SPHostUrl'
));
context =
new
SP.ClientContext(appweburl);
factory =
new
SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite =
new
SP.AppContextSite(context, hostweburl);
var
list = appContextSite.get_web().get_lists().getByTitle(listName);
var
item = list.getItemById(itemID);
var
field = list.get_fields().getByInternalNameOrTitle(fieldName);
var
txField = context.castTo(field, SP.Taxonomy.TaxonomyField);
context.load(field);
context.load(txField);
context.load(item);
context.executeQueryAsync(
function
() {
var
termSetId = txField.get_termSetId().toString();
var
termId;
getTermIdForTerm(
function
success(id) {
termId = id;
var
value = item.get_item(fieldName);
var
terms =
new
Array();
if
(txField.get_allowMultipleValues()) {
var
enumerator = value.getEnumerator();
while
(enumerator.moveNext()) {
var
tv = enumerator.get_current();
terms.push(tv.get_wssId() +
";#"
+ tv.get_label() +
"|"
+ tv.get_termGuid());
}
terms.push(
"-1;#"
+ term +
"|"
+ termId);
termValueString = terms.join(
";#"
);
termValues =
new
SP.Taxonomy.TaxonomyFieldValueCollection(context, termValueString, txField);
txField.setFieldValueByValueCollection(item, termValues);
}
else
{
var
termValue =
new
SP.Taxonomy.TaxonomyFieldValue();
termValue.set_label(term);
termValue.set_termGuid(termId);
termValue.set_wssId(-1);
txField.setFieldValueByValue(item, termValue);
}
item.update();
context.executeQueryAsync(
function
() {
alert(
'field updated'
);
},
function
(sender, args) {
alert(args.get_message() +
'\n'
+ args.get_stackTrace());
});
},
function
(sender, args) {
alert(args.get_message() +
'\n'
+ args.get_stackTrace());
},context, term, termSetId);
},
function
error(err) {
alert(err.get_message());
});
}
function
getTermIdForTerm(success, error, clientContext, term, termSetId)
{
var
termId =
""
;
var
tSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
var
ts = tSession.getDefaultSiteCollectionTermStore();
var
tset = ts.getTermSet(termSetId);
var
lmi =
new
SP.Taxonomy.LabelMatchInformation(clientContext);
lmi.set_lcid(1033);
lmi.set_trimUnavailable(
true
);
lmi.set_termLabel(term);
var
termMatches = tset.getTerms(lmi);
clientContext.load(tSession);
clientContext.load(ts);
clientContext.load(tset);
clientContext.load(termMatches);
context.executeQueryAsync(
function
() {
if
(termMatches && termMatches.get_count() > 0)
termId = termMatches.get_item(0).get_id().toString();
success(termId);
},
function
(sender, args) {
error(args);
});
}
function
getQueryStringParameter(p) {
var
params =
document.URL.split(
"?"
)[1].split(
"&"
);
var
strParams =
""
;
for
(
var
i = 0; i < params.length; i = i + 1) {
var
singleParam = params[i].split(
"="
);
if
(singleParam[0] == p)
return
singleParam[1];
}
}