Showing posts with label JSOM. Show all posts
Showing posts with label JSOM. Show all posts

Monday 23 May 2016

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


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.     });    

Retrieve Popular Documents Programmatically In SharePoint using JSOM and REST API


The popular documents can be viewed manually from the document libraries with the popular items tab. In this article, you will learn how to fetch popular documents based on view counts using JSOM and REST API. This will be applicable for all SharePoint platforms.


Prerequisite:


You have to enable the reporting feature under site collection features in the site to see the popular documents. This data can be retrieved using search queries. Basically this is part of SharePoint analytics. 


Using JSOM:


The Keyword query language in SharePoint helps us getting the popularity results for the items present on the document libraries. The following steps show you detailed view. 
  1. Set and get the necessary context. Using the context, initiate the keyword query function.
    1. var searchContext = new SP.ClientContext();  
    2. var searchQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(searchContext);  
  2. The results can be retrieved using multiple query filters. In this case, I am using path variable to filter the data. This helps us in getting results for one particular library. Multiple document library data can also be viewed by setting the filters with 'and' parameter. Set the query text as below.
    1. searchQuery.set_queryText("path:http://siteurl/Documents”)  
  3. The following syntax helps us in executing the query against the search server by initializing a SearchExecutor instance.
    1. var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(searchContext);  
  4. Initialize the results and execute the request.
    1. searchRes = searchExecutor.executeQuery(searchQuery);  
    2. searchContext.executeQueryAsync(SearchResults, QueryFailed);  
  5. In the success function, expand the result set (searchRes) to see the document results. The following code snippet shows you to parse the search results.
    1. var resultSet = searchRes.m_value.ResultTables[0].ResultRows;  
    2. var popularDocs = new Array();  
    3. for(var i = 0; i < resultSet.length; i++)  
    4. {  
    5.     popularDocs[i] = [resultSet[i].Title,resultSet[i].ViewsLifeTime];  
    6. }  
  6. Then sort the result set on descending order based on the view count using the below logic.
    1. function Sort(a, b) {  
    2.     return (a[1] > b[1] ? -1 : (a[1] < b[1] ? 1 : 0));  
    3. }  
  7. Now popularDocs array will have the result set sorted based on the view count.
    1. popularDocs.sort(Sort);  


Using REST API:


The Search REST API can also be used to fetch the view counts for the documents. Again we will use path parameter to filter the results for one particular document library.
We will build the rest query first. In the query URL, you can set the necessary filters required. The advantage of using REST is sorting can be done by setting sortlist parameter. Please find the below query URL.
This will fetch all the document related items and we will filter out the necessary values using the code logic. JQuery Ajax call is used to fetch the results.
The below code snippet shows the implementation.
  1. $.ajax({   
  2.     url: "/_api/search/query?querytext='path:http://siteurl/Documents'&sortlist='ViewsLifeTime:descending'",   
  3.     method: "GET",   
  4.     headers: {"accept""application/json;odata=verbose",   
  5.     },   
  6.     success: function(data){  
  7.         var restResults = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;  
  8.         var popularRestResults = new Array();  
  9.         for(var i=0;i<restResults.length;i++){  
  10.             popularRestResults[i] = [restResults[i].Cells.results[3]["Value"],restResults[i].Cells.results[20]["Value"]];  
  11.         }  
  12.     },   
  13.     error: function(sender,args){  
  14.     }   
  15. });  
The popularRestResults[0] or restResults[0] will be the most popular document item. The below image shows the necessary results. restResults[i].Cells.results[3]["Value"] gives the title andrestResults[i].Cells.results[20]["Value"] gives the views count for the corresponding item.


Note: The filtering of the result set can be done based on the filter parameters. In this article, you have seen how data can be filtered with very limited set of filtering options. Other filtering like row limits, refiners or select parameters can be used to filter the results further.


Summary:


Thus you have learnt how the view counts for documents under document libraries can be retrieved. With that, you have seen how the most popular documents can be identified. 

Create, Update or Delete List Views using JSOM in SharePoint


The views can be created for a list with manual steps by going through the list settings. The same can be implemented programmatically using several methods. In this article, you will learn how it can be implemented using JavaScript Object Model.

For example, I have created a list called “Test” with two custom columns, Column1 and Column2. By default when you try opening a list in SharePoint, the default view called “All Items” will be rendered. This view will show you three columns. They are Title, Column1 and Column2.





Creating SharePoint list view using JSOM:


In this example, we will see how we can view only our custom columns by filtering the SharePoint list values.
The following flow will show you the implementation.
  1. Load the SP.js files and get the context of site
  2. Get all the views for a specific list present on the site
    1. var listCollection = web.get_lists();  
    2. list = listCollection.getByTitle("Test");  
    3. viewCollection = list.get_views();  
    4. viewContext.load(viewCollection);  
  3. Create a custom view ViewCreationInformation method. Set view title and the fields to be shown on the view using the following code.
    1. var createView = new SP.ViewCreationInformation();  
    2. createView.set_title("TestView");   
    3. var viewFields = ["Column1","Column2"];  
    4. createView.set_viewFields(viewFields);  
  4. Then build your query to retrieve the values for the view. This step can be an optional one.
    1. var camlQuery = new SP.CamlQuery();  
    2. var query = "<Where><Eq><FieldRef Name='Column1' /><Value Type='Text'>2</Value></Eq></Where>";  
    3. camlQuery.set_viewXml(query);  
    4. createView.set_query(camlQuery);
  5. The view can be limited with custom row limit.
    1. createView.set_rowLimit(1);  
  6. The view can be still customized with view types. The applicable types are html, grid, etc. The following code shows you how to set the type.
    1. createView.set_viewTypeKind(2048);  
    The following table shows you different types of field types with values.

     Type Value
     none 0
     html 1
     grid 2048
     calendar 524288
     recurrence 8193
     chart 131072
     gantt 67108864
  7. Then add the view to the collection and execute the query.
    1. viewCollection.add(createView);    
    2. viewContext.load(viewCollection);    
    3. viewContext.executeQueryAsync(ViewCreated, onFail);     
  8. After execution of the above approach, go to List tab and you can see the new view, “Grid View,” created. Click on the new view to see the list with necessary filters set.


    The above steps helped us in creating views for custom list.




Modifying or Updating SharePoint list views using JSOM:


The approach is similar to creating views. Here instead of creating new view object, the existing view is retrieved and the properties are updated. The below code shows how you can update existing views.

Note: There are a few limitations in modifying views, such as the view type and view fields can’t be changed.

The following piece of code will help you in modifying the existing list view we have created above. 
  1. function UpdateViewJSOM(){  
  2.     viewContext = SP.ClientContext.get_current();  
  3.     var web = viewContext.get_web();  
  4.     var listCollection = web.get_lists();  
  5.     list = listCollection.getByTitle("Test");  
  6.     viewCollection = list.get_views();  
  7.     view = viewCollection.getByTitle("GridView");  
  8.   
  9.     var camlQuery = new SP.CamlQuery();  
  10.     var query = "<Where><Eq><FieldRef Name='Column1' /><Value Type='Text'>1</Value></Eq></Where>";  
  11.     camlQuery.set_viewXml(query);  
  12.     view.set_viewQuery(camlQuery);  
  13.     view.set_rowLimit(2);  
  14.     view.update();  
  15.     viewContext.load(view);  
  16.   
  17.     viewContext.executeQueryAsync(ViewModified,  
  18.     function onFail(sender,args){  
  19.         console.log(args.get_message());  
  20.     });  
  21. }  

The following snapshot shows the modified list view.


Deleting SharePoint list views using JSOM:


You will learn how a list view can be deleted. This can be achieved by using deleteObject method. The below code will help you in deleting a view.
  1. function DeleteViewJSOM(){  
  2.     viewContext = SP.ClientContext.get_current();  
  3.     var web = viewContext.get_web();  
  4.     var listCollection = web.get_lists();  
  5.     list = listCollection.getByTitle("Test");  
  6.     viewCollection = list.get_views();  
  7.     view = viewCollection.getByTitle("GridView");  
  8.     view.deleteObject();      
  9.     viewContext.executeQueryAsync(ViewDeleted,  
  10.     function onFail(sender,args){  
  11.         console.log(args.get_message());  
  12.     });  
  13. }