Update Managed Metadata Field in SharePoint 2013


The following example update a term store field that allow multiple values.

using (SPSite site = new SPSite("siteUrl"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
                        PublishingPageCollection pubPages = pubWeb.GetPublishingPages();
                        string metadata = String.Empty;
                        foreach (PublishingPage pubPage in pubPages)
                        {
                            SPListItem item = pubPage.ListItem;

                            if (item.File.CheckedOutByUser != null)
                                item.File.UndoCheckOut();

                            if (pubPage.Name.ToLower() == "test.aspx")
                            {
                                pubPage.CheckOut();
                                TaxonomyField oField = (TaxonomyField)item.Fields.GetFieldByInternalName("fieldInternalName");

                                TaxonomyFieldValueCollection tagValues = new TaxonomyFieldValueCollection(oField);
                                string termString = String.Concat("Technology", TaxonomyField.TaxonomyGuidLabelDelimiter, "84cc2695-08d6-4f2e-a682-76218d313f19");
                             
                                TaxonomyFieldValue tagValue = new TaxonomyFieldValue(string.Empty);
                                tagValue.PopulateFromLabelGuidPair(termString);
                                tagValues.Add(tagValue);

                                termString = String.Concat("End User Technology", TaxonomyField.TaxonomyGuidLabelDelimiter, "826dffdd-4ffb-43e4-88c2-ea86fa4363f5");
                                TaxonomyFieldValue tagValue2 = new TaxonomyFieldValue(string.Empty);
                                tagValue2.PopulateFromLabelGuidPair(termString);
                                tagValues.Add(tagValue2);

                                oField.SetFieldValue(pubPage.ListItem, tagValues);
                                item.Update();
                                pubPage.CheckIn("checking in by tool");                              
                            }                          
                        }
                    }
                }

Comments

Popular posts from this blog

SharePoint 2013 - Working with Display Template for Content Search Web Part

How to Customize MOSS Site Manager (Site Content and Structure Page)

Add spell check dictionary in SharePoint 2010, SharePoint 2013, and Office 365