Retrieving the Source Term for an items field.

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

2 thoughts on “Retrieving the Source Term for an items field.

  1. 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…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s