пятница, 4 марта 2011 г.

Modifying the SharePoint Taxonomy Fields in code

While investigating this issue, I have found several posts that sugested a quite complicated way to modify taxonomy fields through code. Here comes some code that would to exactly that in a quite simple way. I have found this method in internet, but modified it to use the AnchorId of the taxonomy field, as otherwise it won't work with fields that are not mapped to the root of a term store.


public static void SetTaxonomyFieldValue(SPWeb web, SPListItem item, SPField field,
 string value, bool isAddingValuesToTermSetAllowed)
{
    // Gets the taxonomy field instance
    TaxonomyField managedField = field as TaxonomyField;
    // Gets the current taxonomy session
    TaxonomySession session = new TaxonomySession(web.Site, false);
    // Gets the term store (by SspId)
    var termStoreCol = session.TermStores[managedField.SspId];
    // Gets the terms of a specific term set (by TermSetId)
    var parentTerm = termStoreCol.GetTerm(managedField.TermSetId, managedField.AnchorId);
    var termCollection = parentTerm.Terms;
    if (isAddingValuesToTermSetAllowed)
    {
        if (!parentTerm.Terms.Any(t => t.Labels.Any(l => l.Value == value)))
        {
            parentTerm.CreateTerm(value, 1033);
            termStoreCol.CommitAll();
            SetTaxonomyFieldValue(web, item, field, value, false);
            return;
        }
    }
    // Sets the field value using the list of terms
    if (managedField.AllowMultipleValues)
    {
        var listTerms = new List<Term>();
        listTerms.Add(termCollection[value]);
        managedField.SetFieldValue(item, listTerms);
    }
    else
    {
        managedField.SetFieldValue(item, termCollection[value]);
    }
    item.Update();
}




Комментариев нет:

Отправить комментарий