Wednesday, September 11, 2013

Getting Managed Metadata Term from AfterProperties

If you've ever worked with the Managed Metadata Service you'll know how very little documentation or community support there is for it at present. It took me a long time to figure out how to get the corresponding Term from the int value in the AfterProperties or BeforeProperties collection during an ItemUpdating or ItemAdding event. Hope this helps you.


private Term GetTermFromAfterProperties(SPItemEventProperties properties)
{
       TaxonomySession termSession = 
              new TaxonomySession(properties.ListItem.Web.Site);
       TermStore termStore = termSession.TermStores[0];
       Group group = 
              termStore.Groups.Cast<Group>().First(g => g.Name.Equals("GroupName"));
       TermSet termSet = 
              group.TermSets.Cast<TermSet>().First(t => t.Name.Equals("TermSetName"));
                          
       int value = (Int32)properties.AfterProperties["interalFieldName"];  
       // Yes it's an Int, but if you're saving from an office application
       // like MS Word it's a string number like "23"
       SPField field = properties.ListItem.Fields["fieldDisplayName"];
       TaxonomyFieldValue tfv = new TaxonomyFieldValue(value.ToString(), field);

       Guid termGuid = new Guid(tfv.TermGuid);

       Term term = termSet.GetTerm(termGuid);

       return term;
}