How to set managed meta data value when term is under another term
-
08-02-2021 - |
Question
I have a list containing managed meta data field which is reading data from following term store (picture given below):
I am trying to set field value using C# code as below but getting error
Error
Specified argument was out of the range of valid values.\r\nParameter name: index
TaxonomySession taxonomySession = new TaxonomySession(site);
TermStore termStore = taxonomySession.TermStores["Managed Meta Data"];
Group group = termStore.Groups["DemoGroup"];
TermSet termSet = group.TermSets["Contoso Departments"];
Term term = termSet.Terms["Finance"]; //error is on this line
If I change above line to following then it works fine. It seems since Finance is under Accounting so I cannot directly write its name and has to define some kind of path.
Term term = termSet.Terms["Accounting"]; //this line works fine
How do I update value of "Finance"?
Solution
The thing is that in complex structures you could have multiple terms in the same term set with the same label (e.g you could have Finance
under Marketing
as well).
To just pick the first hit based on the label, you could do this:
//....
TermSet termSet = group.TermSets["Contoso Departments"];
TermCollection terms = termSet.GetTerms("Finance", true);
if (terms.Count > 0) {
Term term = terms[0];
}
To get it from the parent, you could get the child term like this:
Term parent = termSet.Terms["Accounting"];
Term term = parent.Terms["Finance"];