Programmatically or with PnP Provisioning setting a default value for a column is not that problem but with Taxonomy columns and its corresponding Termstore termsets things get a bit more complex.
Let my shortly explain why. Assume we have a simple termset (german locations here):
Assume further we have a taxonomy column and apply it a default value of “Hamburg”
then accessing the column with a simple REST call (/_api/web/fields I often use this for investigation) would show us the default property in the following way:
So what about those three values? The second value “Hamburg” indeed is the Label and the third the GUID we might know from the termstore (With PnP Provisioning for instance we can provision whole termsets with pre-created GUIDs. This gives us great control for further dealing with those termsets.
But what about the first number (“2”)?
This is an item ID from a hidden list called “TaxonomyHiddenList“. Each time you select a term from a termset, this term will be written to this list. We can check this by accessing this list. Although it is hidden, we can open it once we know its name (and if we forget the name /_api/web/lists helps us to remember)
The problem now is: A termset exists once in our tenant (we don’t talk about site collection termsets here) but the list is new in every new site collection. And as we do not control the order we are not sure that “Hamburg” will be the 2nd item in the next site collection, too. Or will it be picked at all? That’s the most important problem! We cannot rely that the termset we want to make to the default one already exists in our site collection’s TaxonomyHiddenList.
So we need some kind of an ensure process and the following CSOM-driven Powershell script will do this for us:
We need a site and its Url, the name of our column, the label and the GUID of the term we want to have as default. With that we call our function.
In the function we first access our column. After that we create a TaxonomyFieldValue with our Label and our GUID, as a WssID we use -1.
Finally, and that’s the “heart” of this function, we use the GetValidatedString method of our Taxonomy field instance. The return value will be what we need and have seen above. If the term already existed in the TaxonomyHiddenList it will contain the existing ID of the list item. If it didn’t it would have been inserted now.
The returned string we can use in our code to set the default value or insert in our Provisioning Template if we use PnP Provisioning or another tool. In PnP we can simply transfer the just evaluated string with a parameter like I did with evaluated default groups in my last post, too.