Monday, December 2, 2013

SharePoint Managed Metadata Fields

The steps and rules for getting and setting Managed Metadata fields in SharePoint are not so straightforward. I created this post to help me remember what I have figured out and what works for me. I would like to give a shout out to Matthew Yarlett and his excellent post on various SharePoint field types with PowerShell. I have bookmarked his post for future reference as he covers all field types and some variations on Managed Metadata that I have not covered here.

C# (Console Application)
// <>Partial namespace listing
using Microsoft.SharePoint.Taxonomy; // Must add this reference

// Set some sample variables
string yourservername = "contoso.local";
string yoursitepath = "sites/Accounting/Audits";
string yourlistname = "Contracts";
int youritemid = 34;
string yourtaxfieldcolname = "Client";
string yourtaxsessionname = "Managed Metadata Service";
string yourtaxgroupname = "Accounting Term Store";
string yourtaxsetname = "Client Term Set";
string yournewclient = "Ford";

// <>Code omitted, insert code into Main

// Access the site object
using (SPSite site = new SPSite(string.Format("http://{0}/{1}", yourservername, yoursitepath)))
{

    // Access the web object
    using (SPWeb web = site.OpenWeb())
    {

        // Get taxonomy session variables
        TaxonomySession session = new TaxonomySession(site);
        var store = session.TermStores[yourtaxsessionname];
        var group = store.Groups[yourtaxgroupname];
        var set = group.TermSets[yourtaxsetname];

        // To get all the clients from the term set
        foreach(var term in set.Terms)
        {
            Console.WriteLine(string.Format(" – Term: {0}", term.Name));
        }
        Console.WriteLine();

        // Get a reference to a listitem
        SPList list = web.Lists.TryGetList(yourlistname);
        SPListItem item = list.GetItemById(youritemid);

        // Get the current taxonomy field value
        var taxFieldValuePrev = item[yourtaxfieldcolname] as TaxonomyFieldValue;
        Console.WriteLine(string.Format(" Previous: {0}", taxFieldValuePrev.Label));

        // Update the taxonomy field value to the new value
        var term = set.Terms[yournewclient];
        var taxField = item.Fields[yourtaxfieldcolname] as TaxonomyField;
        taxField.SetFieldValue(item, term);
        item.Update();

        // Get the updated taxonomy field value
        var taxFieldValueNew = item[yourtaxfieldcolname] as TaxonomyFieldValue;
        Console.WriteLine(string.Format(" New: {0}", taxFieldValueNew.Label));

   } // end using web

} // end using site

// Let the user terminate the program
Console.Write("Press return to quit... ");
Console.ReadLine(); 


No comments:

Post a Comment