Navigation Bar

Tuesday 24 May 2011

Provisioning Managed metadata field through Feature in SharePoint 2010

Managed metadata columns is very great feature introduced in SharePoint 2010 to manage in one central place.

Below I am going to illustrate how to use managed metadata field in feature.

To get it working, we need to create two features. 1) for field provision 2) for binding
We can't use binding through declarative way as we don't know what will be GUID for TermSet and TermGroup in new environment or where we are going to deploy. So that's why we need some event handler to find the Guid and associate it with field.

Following is a feature called "Fields Provisioner" to provision a field in declarative way:

when you activate the above feature it will create a Field in SiteColumns gallery but it would not bind to TermStore, so you can't use it.

Below is another feature for binding, let call it "Field Binder":

public override void FeatureActivated(SPFeatureReceiverProperties properties)
using (SPSite site = properties.Feature.Parent as SPSite)
//Field to be linked with TermSet
//Look at element.xml file for these GUID
string fieldGuid = "{930C252B-6CB9-4D37-992F-0B017D751FB3}";
TaxonomyField field = site.RootWeb.Fields[new Guid(fieldGuid)] as TaxonomyField;
TaxonomySession session = new TaxonomySession(site);
TermStore termStore = session.TermStores["Managed Metadata Service"];
int lcid = CultureInfo.CurrentCulture.LCID;
Group taxonomyGroup = termStore.Groups["Project Name"];
TermSet termSet = group.TermSets["Document Category"];

// Connect to Managed Metadata Store
field.SspId = termStore.Id;
field.TermSetId = termSet.Id;
field.TargetTemplate = string.Empty;
field.AnchorId = Guid.Empty;
field.TextField = new Guid(hiddenFieldGuid);

Once it is binded, you can use in any lists/document libraries or content types.
In above code I am using TaxonomyRepository, which contains few methods to get the GUID of TermSet, TermGroup and TermStore.

Following is the snapshot of project structure:

After activating the feature, you would see similar result shown below:


Updated: Included field xml as well.

No comments:

Post a Comment