SharePoint 2010 Managed Metadata columns programatically
2 March 2011
You can provision managed metadata column into the content type.
You need to add the “Metadata” column into the site columns and content type using element xml file, and also need to connect the field to metadata column in the feature activation.
Here is the solution
1. You need to add a new field element of the type “TaxonomyFieldType”.
<xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Field ID="{46138ADB-1778-4E05-8371-114006F725A0}" Type="TaxonomyFieldType" DisplayName="Locations" ShowField="Term1033" Required="TRUE" EnforceUniqueValues="FALSE" Group="_Custom" StaticName="Locations" Name="Locations" /> </Elements>
2. Add this filed to the content type, just need to add a new “FieldRef”
<FieldRef ID="{46138ADB-1778-4E05-8371-114006F725A0}" Name="Locations"/>
3. Now we have to connect this field to managed metadata service(MMS).
For this we need to create an event receiver for the feature. Right click on the feature
and select “Add event receiver”.
Uncomment the “feature activate” code and replace it with the following code.
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; Guid fieldId = new Guid(“{46138ADB-1778-4E05-8371-114006F725A0}" if (site.RootWeb.Fields.Contains(fieldId)) { TaxonomySession session = new TaxonomySession(site); if (session.TermStores.Count != 0) { var termStore = session.TermStores["Managed Metadata Service"]; var group = termStore.Groups.GetByName("Locations Group"); var termSet = group.TermSets["Towns"]; TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField; field.SspId = termSet.TermStore.Id; field.TermSetId = termSet.Id; field.TargetTemplate = string.Empty; field.AnchorId = Guid.Empty; field.Update(); } } }
This method will check if the field has been deployed. We used Guid to retrieve the filed as defined in the XML. Your term store group definition should look like this.
If it is different then you need to change the “group name” and “term set” name in the feature activation according to your MMS environment.
Now you deploy your content type and can test it by creating a new list from that content type.
The result with the metadata column is shown in the below picture.