Sunday, April 3, 2011

Programatically Setting Column Default Value for Managed Metadata Column

I've been working on setting up document libraries with different column default values for managed metadata based on what site the library is in.  I achieved this with the following:  
  
        using (SPSite siteCollection = new SPSite("http://www.yoursite.com"))
        {
            using (SPWeb web = siteCollection.OpenWeb("/yourweb/"))
            {
                SPList customDocumentLibrary = web.Lists["Documents"];
                SPFolder rootFolder = customDocumentLibrary.RootFolder;

                MetadataDefaults columnDefaults = new MetadataDefaults(customDocumentLibrary);

                columnDefaults.RemoveAllDefaults();
                columnDefaults.SetFieldDefault(rootFolder, "Programs", "1033;#Academics|bc943091-79ac-4f5f-a79b-205e8e717823");
                columnDefaults.Update();
            }
        }

Note that if you don't add the proper value in the correct format you'll get the following error message:
 
The given value for a taxonomy field was not formatted in the required <int>;#
 
Where int is the lcid, label is the Term Name, and the Guid is the Term Guid.

1 comment:

Cooney said...

hi Sean,
how do you determine the GUID value for the term that you are going to apply as the default value ?

If when i'm writing my powershell script I don't know what the ID is is there any way I can get powershell to find the id based on the term name itself ?