In the earlier articles, we saw many interesting facts about the Taxonomy Fields. In this article, let us see how to Insert, Update Taxonomy Field Programmatically using C#.
There are two types we need to consider. One is single value Taxonomy Field and the other is Multi Value Taxonomy Field.
Let us see how to insert a Single Value Taxonomy Field.
SPListItem navigationListItem = navigationList.Items.Add();
SPField spfldTerm = navigationListItem.Fields.TryGetFieldByStaticName(<<StaticName of the Taxonomy Field>>);
TaxonomyField txfldTerm = (TaxonomyField)spfldTerm;
TaxonomyFieldValue taxonomyValue = new TaxonomyFieldValue(txfldTerm);
taxonomyValue.TermGuid = <<Term GUID>>.ToString();
taxonomyValue.Label = <<Term Name>>.Name;
navigationListItem[txfldTerm.Id] = taxonomyValue;
navigationListItem[txfldTerm.TextField] = taxonomyValue;
On the above code snippet, the Term GUID and Term Name will be the ID and Name of the Term.
Now, let us see how to insert a Multi Value Taxonomy Field. There is no much difference between insert and updating the Taxonomy field.
The Insert of Multi Value Taxonomy Field is as follows.
for(int i=0; $i < arrayCount; $i++)
{
TaxonomyFieldValue GeoTagSecondaryFieldValue = new Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue(GeoTagSecondaryField)
GeoTagSecondaryFieldValue.TermGuid = array[$i]
GeoTagSecondaryFieldValue.Label = array[$i]
GeoTagSecondaryFieldValueCollection.Add($GeoTagSecondaryFieldValue)
}
GeoTagSecondaryField.SetFieldValue(newItem, GeoTagSecondaryFieldValueCollection) ;
The same can be done using the PowerShell as well.
#Single Value :
$newItem = $list.Items.Add()
$BookShelvesField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$newItem.Fields["BookShelf"]
$BookShelvesFieldValue = new-object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($BookShelvesField)
$BookShelvesFieldValue.TermGuid = $_.BookShelveTermGUID
$BookShelvesFieldValue.Label = $_.BookShelveTermLabel
$BookShelvesField.SetFieldValue($newItem, $BookShelvesFieldValue)
#And the Multi Value is like
$GeoTagSecondaryCount = $GeoTagSecondaryTermIDArray.Length
for($i=0; $i -lt $GeoTagSecondaryCount; $i++)
{
write-host $GeoTagSecondaryTermIDArray[$i]
$GeoTagSecondaryFieldValue = new-object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($GeoTagSecondaryField)
$GeoTagSecondaryFieldValue.TermGuid = $GeoTagSecondaryTermIDArray[$i]
$GeoTagSecondaryFieldValue.Label = $GeoTagSecondaryTermLabelArray[$i]
$GeoTagSecondaryFieldValueCollection.Add($GeoTagSecondaryFieldValue)
}
$GeoTagSecondaryField.SetFieldValue($newItem, $GeoTagSecondaryFieldValueCollection)
$newItem.Update()
Happy Coding,
Sathish Nadarajan.
Leave a comment