views:

683

answers:

1

The situation:

I have a bunch of Terms in the Term Store and a list that uses them.

A lot of the terms have not been used yet, and are not available yet in the TaxonomyHiddenList. If they are not there yet they don't have an ID, and I can not add them to a list item.

There is a method GetWSSIdOfTerm on Microsoft.SharePoint.Taxonomy.TaxonomyField that's supposed to return the ID of a term for a specific site.

This gives back IDs if the term has already been used and is present in the TaxonomyHiddenList, but if it's not then 0 is returned.

Is there any way to programmatically add terms to the TaxonomyHiddenList or force it happening?

+1  A: 

On MSDN you can find how to create a Term and add it to TermSet. Sample is provided from TermSetItem class description. TermSet should have a method CreateTerm(name, lcid) inherited from TermSetItem. Therefore you can use it in the sample below int catch statement ie:

catch(...)
{
   myTerm = termSet.CreateTerm(myTerm, 1030);
   termStore.CommitAll();
}

As for assigning term to list, this code should work (i'm not sure about the name of the field "Tags", however it's easy to find out the proper internal name of the taxonomy field):

using (SPSite site = new SPSite("http://myUrl")) 
{
    using (SPWeb web = site.OpenWeb())
    {
        string tagsFieldName = "Tags";
        string myListName = "MyList";
        string myTermName = "myTerm";

        SPListItem myItem = web.Lists[myListName].GetItemById(1);
        TaxonomyField tagsField = (TaxonomyField) myList.Fields[tagsFieldName];
        TaxonomySession session = new TaxonomySession(site);
        TermStore termStore = session.TermStores[tagsField.SspId];
        TermSet termSet = termStore.GetTermSet(tagsField.TermSetId);
        Term myTerm = null;

        try
        {
            myTerm = termSet.Terms[myTermName];
        }
        catch (ArgumentOutOfRangeException)
        {
            // ?
        }

        string termString = String.Concat(myTerm.GetDefaultLabel(1033),
                                            TaxonomyField.TaxonomyGuidLabelDelimiter, myTerm.Id);

        if (tagsField.AllowMultipleValues)
        {
            TaxonomyFieldValueCollection tagsValues = new TaxonomyFieldValueCollection(tagsField);
            tagsValues.PopulateFromLabelGuidPairs(
                String.Join(TaxonomyField.TaxonomyMultipleTermDelimiter.ToString(),
                            new[] { termString }));
            myItem[tagsFieldName] = tagsValues;

        }
        else
        {
            TaxonomyFieldValue tagValue = new TaxonomyFieldValue(termString);
            myItem[tagsFieldName] = tagValue;
        }
        myItem.Update();
    }
}
Gutek