Search code examples
javascripttaxonomysharepoint-2013csom

Create Taxonomy sub-term using CSOM and javascript


in sharepoint managed metadata I found very little documentation on managing terms using javascript CSOM. I could create a taxonomy term directly under the term set but I want to create a term under another term as a child like in term store window.

function createTerm(){
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Term Store under which to create the term.
var termStore = termStores.getByName("Taxonomy_Dmxzz8tIBzk8wNVKQpJ+xA==");
//Term Set under which to create the term.
var termSet = termStore.getTermSet("b49f64b3-4722-4336-9a5c-56c326b344d4");
//Name of the term, LCID and a new GUID for the term.
var newTerm = termSet.createTerm("India", 1033, "b49f64b3-4722-4336-9a5c-56c326b344a9");
//newTerm.set_isAvailableForTagging(true);
context.load(newTerm);
context.executeQueryAsync(function(){
alert("Term Created: " + newTerm.get_name());
 },function(sender,args){
console.log(args.get_message());
});
}

Solution

  • In order to add term under a parent term, you need:

    • The Term store ID and relevant Term set
    • The Parent Term ID (to which the new child term will be added)

    The code:

     function execOperation()
     {
        //Current Context
        var context = SP.ClientContext.get_current();
    
        //Current Taxonomy Session
        var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
    
        //Term Stores
        var termStores = taxSession.get_termStores();
    
        //Term Store under which to create the term.
        var termStore = termStores.getByName("Taxonomy_Dmxzz8tIBzk8wNVKQpJ+xA==");
    
        //Term Set under which to create the term.
        var termSet = termStore.getTermSet("b49f64b3-4722-4336-9a5c-56c326b344d4");
    
    
        //get the parent term ID, say it's "cf46hujkl-3344-4336-9a5c-56c326b344d4"
        var parentTerm = termSet.getTerm("cf46hujkl-3344-4336-9a5c-56c326b344d4");
    
        //create new child term under the parent term
        var newTerm = parentTerm.createTerm("SharePoint Rocks", 1033, newGuid.toString());
    
        context.load(newTerm);
        context.executeQueryAsync(function(){
        alert("Term Created: " + newTerm.get_name());
         },function(sender,args){
        console.log(args.get_message());
        });}