Tuesday, December 29, 2015

Set value to an Managed Metadata field


Managed Metadata is an extraordinary feature in SharePoint career path. It helps organization to structure all unstructured data and it is easy to use them.

The managed metadata field can be associated with List, document library.. etc

Also it has a feature that not used values(terms) can be deprecated instead deleting them permanently from centralized location. The deprecated terms can be used for future tracking. Normally if any MMD field associated with a TermSet then user can see only Enabled terms in the TermStore tree. It is a out-of-the-box feature that SharePoint will apply filter and display only enabled terms to the end user.

But deprecated term also can be assigned to a MMD field if necessary based on business need using Server Object model.

Find the code sample below which assign value to MMD field with enabled and deprecated term.

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace SetMMD_Field {

    class Program {
        static void Main(string[] args) {
            SPList lst = null; ;
            
            using (SPSite site = new SPSite(@"http://kmstechs/")) {
                using (SPWeb web = site.RootWeb) {
                  //  SPSecurity.RunWithElevatedPrivileges(delegate() {
                        lst = web.Lists["SK_Test"];
                        SPListItem oSPListItem = lst.Items.Add();
                        oSPListItem["Title"] = "Hello SharePoint";
                        TaxonomySession session = new TaxonomySession(site);

                        TaxonomyField taxfield = oSPListItem.Fields["Invalid_MMD"] as TaxonomyField;

                        Term InvalidTerm = session.GetTerm(new Guid(@"7dba48a0-89fa-4203-a265-e49ca3752ab7"));
                        string taxFieldInternalname1 = oSPListItem.Fields["Invalid_MMD"].InternalName;
                        oSPListItem[taxFieldInternalname1] = InvalidTerm.Name + "|" + InvalidTerm.Id.ToString();
                        taxfield.SetFieldValue(oSPListItem, InvalidTerm);

                        TaxonomyField taxfield2 = oSPListItem.Fields["Valid_MMD"] as TaxonomyField;

                        Term validTerm = session.GetTerm(new Guid(@"dca67b77-e4f4-4630-8785-e22518945ecc"));
                        string taxFieldInternalname2 = oSPListItem.Fields["Valid_MMD"].InternalName;
                        oSPListItem[taxFieldInternalname2] = validTerm.Name + "|" + validTerm.Id.ToString();
                        taxfield2.SetFieldValue(oSPListItem, validTerm);

                        oSPListItem.Update();

                   // });
                }
            }

            Console.WriteLine("done");

            Console.ReadKey(true);
        }
    }
}

Enjoy working with SharePoint :-)

No comments:

Post a Comment