Monday, 1 November 2010

Some TaxonomyField things and code

Before a new term can be used for tagging in a web site it needs to be added to the hidden list "TaxonomyHiddenList".
Several suggestions how to add a new term with code has been posted and this is my conclusion:

Adding a new term to an item:

TaxonomyField tf = item.Fields["ColumnName"] as TaxonomyField;

This doesn´t work for new items:

int hiddenTermId = -1;
int[] wssIds = TaxonomyField.GetWssIdsOfTerm(site, TermStore.Id, TermSet.Id, Term.Id, false, 1);

if(wssIds.Length > 0)
hiddenTermId = wssIds[0];

TaxonomyFieldValue tfv = new TaxonomyFieldValue(termId + ";#" + term.Name + TaxonomyField.TaxonomyGuidLabelDelimiter + term.Id.ToString())

or this:

string termString = String.Concat("-1", SPFieldMultiColumnValue.Delimiter, term.GetDefaultLabel(1033));
TaxonomyFieldValue tfv = new TaxonomyFieldValue(termString);

Add a comment if you have any question.

No comments: