Karine Bosch’s Blog

On SharePoint

Programmatically provisioning a TaxonomyField of type TaxonomyFieldTypeMulti


I had a hard time finding out how I could save multiple terms to a field of TaxonomyFieldTypeMulti using the SharePoint server object model.

The following code worked out for me:

        private static void SetTaxonomyValue(SPListItem item, Term term, string fieldName)

        {

            if (term != null && item != null && item.Fields[fieldName] != null)

            {

                if (item.Fields[fieldName].TypeAsString == "TaxonomyFieldType")

                {

                    TaxonomyField taxonomyField = item.Fields[fieldName] as TaxonomyField;

                    TaxonomyFieldValue taxvalue = new TaxonomyFieldValue(taxonomyField);

                    taxvalue.TermGuid = term.Id.ToString();

                    taxvalue.Label = term.Name;

                    item[fieldName] = taxvalue;

                }

                else if (item.Fields[fieldName].TypeAsString == "TaxonomyFieldTypeMulti")

                {

                    TaxonomyField taxonomyField = item.Fields[fieldName] as TaxonomyField;

                    TaxonomyFieldValueCollection taxvalues = 

item[fieldName] as TaxonomyFieldValueCollection;

                    if (taxvalues == null)

                        taxvalues = new TaxonomyFieldValueCollection(taxonomyField);

                    TaxonomyFieldValue taxvalue = new TaxonomyFieldValue(taxonomyField);

                    taxvalue.TermGuid = term.Id.ToString();

                    taxvalue.Label = term.Name;

                    taxvalues.Add(taxvalue);

                    item[fieldName] = taxvalues;

                }

            }

        }

 

When the taxonomy field is of type TaxonomyFieldTypeMulti, terms are stored as a TaxonomyFieldValueCollection. The trick is that you first have to test whether you already have a term available in the collection or not. If not, you have to initialize the collection, otherwise you will get a “null reference” exception when you try to add a term to the collection.

December 19, 2013 - Posted by | SharePoint 2010, SharePoint 2013

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: