Reputation: 436
I am trying to retrieve terms from term store using JavaScript, it work just a fine with this code: Get the label of single taxonomy field:
var fieldValue = item.get_item("FieldName");
var fieldLabel = fieldValue.Label;
I have one issue to retrieve labels of a multi-value Taxonomy Field? I've tried this
var fieldValue = item.get_item("FieldName");
var taxEnumerator = fieldValue.getEnumerator();
while(taxEnumerator.moveNext()){
var currentTerm = taxEnumerator.get_current();
var label = currentTerm.Label;
// do something with the label here
}
But it doesn't work
Upvotes: 0
Views: 4828
Reputation: 59328
Most likely you are getting this error since sp.taxonomy.js
library has not been loaded and in that case taxonomy field value is returned as "lightweight" object (not of SP.Taxonomy.TaxonomyFieldValueCollection object type).
Option 1 (recommended): getting getting multiple taxonomy field values with sp.taxonomy
library
First of all, I would recommend this approach since SP.Taxonomy
namespace provides not only a standard way for dealing with taxonomy field values but also a way of working with Managed Metadata API via JSOM.
The following example shows how to:
Example:
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', function () {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var fieldVal = item.get_item(fieldName);
for(var i = 0; i < fieldVal.get_count(); i++) {
var label = fieldVal.get_item(i).get_label();
var guid = fieldVal.get_item(i).get_termGuid();
//...
}
},
function(sender,args){
console.log(args.get_message());
});
});
Option 2: getting multiple taxonomy field values without sp.taxonomy.js
library loaded
When sp.taxonomy
library is not loaded, taxonomy field value could still be retrieved via _Child_Items_
property as demonstrated below:
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var fieldVal = item.get_item(fieldName)._Child_Items_;
for(var i = 0; i < fieldVal.length; i++) {
var label = fieldVal[i].Label;
var guid = fieldVal[i].TermGuid;
//...
}
},
function(sender,args){
console.log(args.get_message());
});
Upvotes: 3