Last active
January 10, 2016 16:12
-
-
Save arjancornelissen/acc4b0083954757f7168 to your computer and use it in GitHub Desktop.
Content type with Managed Metadata Feature receiver02
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Set the correct values for an Managed Metadata field | |
/// </summary> | |
/// <param name="site"><see cref="SPSite"/> object</param> | |
/// <param name="fieldId"><see cref="GUID"/> from the field to be updated</param> | |
/// <param name="Termstore">Name of the Term Store</param> | |
/// <param name="TermGroup">Name of the Term Group</param> | |
/// <param name="Termset">Name of the Term set</param> | |
private void SetTaxonomyField(SPSite site, Guid fieldId, string TermGroup, string Termset, string Term) | |
{ | |
if (site.RootWeb.Fields.Contains(fieldId)) | |
{ | |
TaxonomySession session = new TaxonomySession(site); | |
if (session.DefaultKeywordsTermStore != null) | |
{ | |
var termStore = session.DefaultKeywordsTermStore; | |
var group = termStore.Groups.GetByName(TermGroup); | |
var termSet = group.TermSets[Termset]; | |
var termSetID = termSet.Id; | |
Guid anchorId = new Guid(); | |
if (!string.IsNullOrEmpty(Term)) | |
{ | |
Term anchor = termSet.GetTermByPath(Term); | |
anchorId = anchor.Id; | |
} | |
TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField; | |
// Connect to MMS | |
field.SspId = termSet.TermStore.Id; | |
field.TermSetId = termSetID; | |
if (anchorId != new Guid()) | |
field.AnchorId = anchorId; | |
field.TargetTemplate = string.Empty; | |
field.Update(); | |
} | |
else | |
{ | |
throw new TermStoreOperationException(string.Format("DefaultKeywordsTermStore not found in site: {0}", site.Url)); | |
} | |
} | |
else | |
{ | |
throw new ArgumentException(string.Format("Field {0} not found in site {1}", fieldId, site.Url)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment