The basic idea of the article is to show how we can automate the mapping process of the term set to the site columns.
Load the required script files with the following snippet:
Here, we will see how we can retrieve the term sets from the metadata termstore and assign it to the metadata site column.
Get Term Set:
Let us first see how we can retrieve the term set from the taxonomy term store, using the term store name and the term set name.
- Get the current context of the site. Using taxonomy and taxonomy session objects, get the taxonomy session of the current site context.
- From the taxonomy session, get the term stores. From the term store collection, retrieve the exact term store by using the term store name. In our case, the term store name is "Managed Metadata Service".
- From the term store; retrieve the groups. From the groups collection; retrieve the exact group by passing the group name. In our case, the group name is "Testing".
- From the group, retrieve all the term sets. From the term set collection, get the respective term set by passing the term set name. The term set name in our case is "Test".
- Load the term store, the term set objects and execute with the context to retrieve the required values. Here, we require the term store ID and term set ID. These properties are used to assign to the metadata site column properties.
Here, the names are used for the term store and the term set instead of IDs, because the term store ID and term set id will change from Server to Server and the names will be the same. The names are common, because the users add it to the taxonomy store.
Mapping Term Set to Site Column:
Now, we will see how we can map the above term set to the site column.
- Get the current context of the site, retrieve the Web object and from the object, get the fields collection.
- Using field collections, retrieve the exact column by name with getByName method. In this case, column name is "TestColumn".
- Cast the field to the taxonomy field. In the taxonomy field, set the term set ID and the term store ID of the term set. (Use values from the section, given above).
- Update and execute the query with the context to finalize the changes.
The above operation will just set the term set to metadata site column at the site level. The columns inherited at the list level will not be changed. To make the changes of the site columns at the list level, we need to use the updateAndPushChanges(true), instead of update() method.
Now, if you open the site column, you will see the term set called "Test" is mapped to the site column "TestColumn" in the term set settings section.
The code snippet given below shows the entire view for the operations, mentioned above.
Note: This is applicable for SharePoint 2013 or SharePoint 2016 or SharePoint online sites.