Recently I’ve been having a hard time dealing with managed metadata default values. I’ve been trying to set default values with a piece of code from SharePoint 2010. I guess this is one out of few places where things got changed from previous version.

First things first – scenario: Users add an item to the list. Then an event receiver creates a site collection. 2 managed metadata fields in the newly created site need to have default values set.

This was doable with a fewer lines of code in SharePoint 2010:

1. Get the term and format a default value. Notice the “-1;#” in String.Format(). This is what causes problems in SharePoint 2013:

[..Some code omitted for briefness..]
var terms = placesTermSet.GetTerms(“Altis”, true);
var defaultTerm = terms[0];
var defaultValue = String.Format(“-1;#{0}{1}{2}”, defaultValue.Labels[0].Value, TaxonomyField.TaxonomyGuidLabelDelimiter, defaultValue.Id);

2. Assign it to the DefaultValue property of the field and update it:

field.DefaultValue = defaultValue;
field.Update(true);

SharePoint 2013 in this case doesn’t like the “-1;#” anymore. This should be replaced with a WssId – a unique term ID from TaxonomyHiddenList. This is unique for every site collection. We need to get that before assigning a default value:

1. Get the taxonomy field which will have the default value:

var field = targetSite.Fields.GetFieldByInternalName(“Places”) as TaxonomyField;
var fieldValue = new TaxonomyFieldValue(field);

2. Get the term which will be used as a default:

[..Some code omitted for briefness..]
var terms = placesTermSet.GetTerms(“Altis”, true);
var defaultTerm = terms[0];

3. Get the WssId, format a default value string, assign it and update the field:

fieldValue.TermGuid = Convert.ToString(defaultTerm.Id);
var dummy = fieldValue.ValidatedString;
if (dummy != null)
{
var defaultValue = String.Format(“{0};#{1}{2}{3}”, fieldValue.WssId, defaultValue.Labels[0].Value, TaxonomyField.TaxonomyGuidLabelDelimiter, defaultValue.Id);
field.DefaultValue = defaultValue;
field.Update(true);
}

Hope this helps!

Paul.