Wednesday, 4 July 2012

Get/Set Values for Managed MetaData Field

Get Terms from the Field:
TaxonomyField commodityGrpFld = (TaxonomyField)web.Fields[“FieldName”];
       // get the Term Store ID from the field
       Guid commodityGrptermStoreId = commodityGrpFld.SspId;
       // Open a taxonomysession and get the correct termstore
       TaxonomySession session = new TaxonomySession(oSite);
       TermStore termStore = session.TermStores[commodityGrptermStoreId];               
       #region get terms from commodity termset
           TermSet termSetCommodity = termStore.GetTermSet(commodityGrpFld.TermSetId);                   
           if (termSetCommodity != null)
               TermCollection CommodityTermColl = termSetCommodity.Terms;
               ArrayList commodityList = new ArrayList();
               foreach (Term commTerm in CommodityTermColl)
//binding to listbox
               lbCommodityGrp.DataSource = commodityList;
        catch (Exception)
        { }
Update the Item value for Managed Metadata field:
TaxonomyField taxoField_Commodity =spfile.Item.Fields[[“FieldName”] as TaxonomyField;
        TaxonomySession taxoSession = new TaxonomySession(oSite);
        TermStore store = taxoSession.TermStores[taxoField_Commodity.SspId];
        TermSet termSet = store.GetTermSet(taxoField_Commodity.TermSetId);
        if (taxoField_Commodity.AllowMultipleValues)
          TermCollection terms = termSet.GetAllTerms();
          List<string> taxonomyValueList = new List<string>();
          foreach (ListItem item in lbCommodityGrp.Items)
            if (item.Selected)
          TaxonomyFieldValueCollection fieldValues = new TaxonomyFieldValueCollection(taxoField_Commodity);
          foreach (Term term in terms)
             if (taxonomyValueList.Contains(term.Name))
                TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(taxoField_Commodity);
                fieldValue.TermGuid = term.Id.ToString();
                fieldValue.Label = term.Name;
          taxoField_Commodity.SetFieldValue(spfile.Item, fieldValues);
Get the Item value for Managed Metadata field:
                We need to convert the item value to TaxonomyFieldValueCollection

1 comment:

  1. Try not to become a man of success, but rather try to become a man of value. See the link below for more info.