[Important News!]
I’ve kicked off a new project/band where I’m creating music with a heavier techno/metal sound called binarywaste. You should check it out by clicking right here!
I’m working on a project where I needed to get back to the term properties for various fields of a SPListItem that are based on a managed metadata column.
The actual process of getting back to a fields source term turned out to be rather simple, as the TaxonomyFieldValue object gives you everything you need.
I thought others might find this useful, so I present my GetTerm method here. This sample is provided as an Extension method, but you certainly can use it standalone if you wish.
using System; using Microsoft.SharePoint; using Microsoft.SharePoint.Taxonomy; namespace krichie.ExtensionMethods { public static class Extensions { /// <summary> /// Retrieves the Source Term for an items field. /// </summary> /// <param name="item" />The item to inspect</param> /// <param name="fieldName" />The name of the field</param> /// <returns>The Taxonomy term</returns> public static Term GetTerm(this SPListItem item, string fieldName) { Term term = null; TaxonomyField field = item.Fields[fieldName] as TaxonomyField; // if this is not a TaxonomyField throw a new exception if (field == null) throw new Exception(fieldName + " is not of type" + " Microsoft.SharePoint.Taxonomy.TaxonomyField."); TaxonomyFieldValue value = item[fieldName] as TaxonomyFieldValue; if (value != null) { TaxonomySession session = new TaxonomySession(item.ParentList.ParentWeb.Site); if (session.TermStores.Count != 0) { TermStore store = session.TermStores[field.SspId]; TermSet set = store.GetTermSet(field.TermSetId); // Get the term using the distinct TermGuid. // If you were to just use set.Terms[fieldName], // you would only examine the root of the term set. term = set.GetTerm(new Guid(value.TermGuid)); } } return term; } } }
HTH!
– Keith
Thanks for such a nice article..
Useful code.
Most of the time I am getting null in this line of code
TaxonomyFieldValue value = item[fieldName] as TaxonomyFieldValue
is there any common reasons I am missing…