Monday, 23 May 2016

Retrieve Or Add Tags From/To SharePoint List Item Using JSOM

Views

In this article, you will learn how to add or get the values from metadata column of SharePoint list item. The metadata values can be retrieved and inserted from SharePoint Metadata and stored into metadata column of a list. Each tag has a label with unique id called GUID.

Note: You have to enable the enterprise metadata and keywords settings before proceeding with this example.

Load the required script files with the following snippet.
  1. ExecuteOrDelayUntilScriptLoaded(LoadTaxonomyScript, "sp.js");  
  2. ExecuteOrDelayUntilScriptLoaded(GetAvailableTags, "SP.Taxonomy.js");  



Get Taxonomy column values:


Here, you will see how to get the tag or metadata column values present already in a SharePoint list item.
Access the list and execute the query
  1. listContext = SP.ClientContext.get_current();  
  2. var listWeb = listContext.get_web();  
  3. var listCollection = listWeb.get_lists();  
  4. list = listCollection.getByTitle("Documents");  
  5. listItem = list.getItemById(1);  
  6. listContext.load(listItem);  
  7. listContext.executeQueryAsync(ListResults,QueryFailed);  
Access the result items set and get the results.
  1. var tagItem = listItem.get_item("TaxKeyword");  // Get the values from metadata column
  2. var tagData = tagItem.get_data();  
  3. var itemTags = new Array();  
  4. for(var i = 0; i<tagData.length;i++){  
  5.         itemTags[i] = [tagData[i].get_label(),tagData[i].get_termGuid()];  //Get Tag name and id
  6. }  
The metadata values can be inserted into SharePoint list items with existing tags or by creating new tag. The tag present in site metadata store can be retrieved and inserted into list item column.


Get tags from Metadata store:


The following steps will help you in getting the tags present already in managed metadata store.
  • Get access to taxonomy session object and using getTaxonomySession method, get the session object.
    1. var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(listContext);  
  • Get the term store data using the session object and getDefaultSiteCollectionTermStore method. Get the term sets with getTermSetsByName method and termset name. Then, get all terms present in the term store.
    1. var termStore = taxonomySession.getDefaultSiteCollectionTermStore();  
    2. var termSets = termStore.getTermSetsByName(termSetName, locale);  
    3. var termSet = termSets.getByName(termSetName);  
    4. var terms = termSet.getAllTerms();  
  • Execute the query and get the terms
    1. listContext.executeQueryAsync(function onSuccess() {  
    2. var enumerator = terms.getEnumerator();  
    3.   
    4.     while (enumerator.moveNext()) {  
    5.         var term = enumerator.get_current();  
    6.         tagsArray.tags.push({ name: term.get_name(), id: term.get_id() });  
    7.         tagsAvailable.push(name);  
    8.     }  
    9. }, QueryFailed);  
  • You can see the available tags in two arrays.


Set Tags in to Metadata column of SharePoint list:


The following steps will help you in setting the tag values in the metadata column of a list item.
  • After getting the list item, get the taxonomy field to set the term set values. The field must be cast to taxonomy.
    1. tagField = list.get_fields().getByInternalNameOrTitle("TaxKeyword");  
    2. tagValues = listContext.castTo(tagField, SP.Taxonomy.TaxonomyField);  
  • Load and execute the query to get the list item and the available tags.
  • Check and add the existing tag values with their id’s into new variable.
  • Add the new tag value along with tag id to the tag value above.Note: The new tag value can be inserted by generating new term id. In this example, I am adding a tag which we have retrieved from the metadata store. Refer above section to get the value from metadata store.
  • Set the tag values and execute the query
    1.     listContext.load(tagValues);    
    2.     listContext.load(listItem);    
    3.     
    4.     listContext.executeQueryAsync(function () {    
    5.     var tagItem = listItem.get_item("TaxKeyword");    
    6.         var tagData = tagItem.get_data();    
    7.         var itemTags = new Array();    
    8.         for(var i = 0; i<tagData.length;i++){    
    9.            itemTags[i] = [tagData[i].get_label(),tagData[i].get_termGuid()]// Item tag values
    10.         }    
    11.     var existingTag = "";
    12.     // Tag values are put into single variable         
    13.     for(var i=0;i<itemTags.length;i++){    
    14.         existingTag += "-1;#" + itemTags[i][0] + "|" + itemTags[i][1] + ";#";    
    15.     }     
    16.     // Checks if the tag already present and initializes the tag value.
    17.     if (!existingTag.endsWith(';#') && existingTag != '') {    
    18.             existingTag = existingTag + ";#";    
    19.         }    
    20.     
    21.         existingTag += "-1;#"+tagsArray.tags[0].name+"|" + tagsArray.tags[0].id; //Here you can also set your own tag with new GUID 
    22.             var termValues = new SP.Taxonomy.TaxonomyFieldValueCollection(listContext, existingTag, tagValues); 
            // Sets/Updates the tag values into metadata field
    23.             tagValues.setFieldValueByValueCollection(listItem, termValues);    
    24.             listItem.update();    
    25.             listContext.load(listItem);    
    26.             listContext.load(tagValues);    
    27.             listContext.executeQueryAsync(function(){    
    28.     },QueryFailed);    
    29.     });