How to create taxonomy field with CSOM
If you need to programmatic create a taxonomy field, you need to:
- Know the termstore id and termset id that associated with this column
- Create a taxonomy field with schema include some basic attributes
- Update some essential attributes for the taxonomy field
//Add field as xml with some basic attribute XElement fieldSchema = new XElement("Field"); fieldSchema.SetAttributeValue("Type", "TaxonomyFieldType"); fieldSchema.SetAttributeValue("DisplayName", "TestField"); list.Fields.AddFieldAsXml(fieldSchema.ToString(), true, AddFieldOptions.DefaultValue); context.ExecuteQuery(); //get taxonomy field context.Load(list.Fields, fields => fields.IncludeWithDefaultProperties().Where(f => f.Title == "TestField")); context.ExecuteQuery(); var taxonomyField = list.Fields[0] as TaxonomyField; //Update essential attributes for taxonomy field // Specify the Id of termset associated with the column taxonomyField.TermSetId = new Guid("a518b741-e2eb-429a-8dc7-f737945b25a3"); // Id of the term store taxonomyField.SspId = new Guid("151320eb-50d2-468d-b42e-1531301953a7"); taxonomyField.Update(); context.ExecuteQuery();
How to update taxonomy field value with CSOM
If you need to programmatic update taxonomy field value, you need to get the term id and label first. This sample shows how to update taxonomy field with multiple values.
ListItem item = list.GetItemById(1); TaxonomyFieldValueCollection col = new TaxonomyFieldValueCollection(context, "", taxonomyField); col.PopulateFromLabelGuidPairs("invrev-mel|44c3035c-b84b-4da3-b7fc-1097ab5e07e2;BEE|c0e6e20a-142f-4f07-ac10-3cf1aa692b13;05 Industry Data and News|b4030964-270b-4f80-bedd-0c2d9d7fae22"); taxonomyField.SetFieldValueByValueCollection(item, col);