Working With Views In SharePoint Using JavaScript Object Model

SharePoint Views are yet another implementation by which, we can organize the data within a list/library. A list can contain millions of items and we might be really concerned about only a minor subset of that data. In order to work with the subset of the main data, we create a view, which satisfies out the requirement by conditionally retrieving the data, based on certain columns within the list.

filter

We can create the views and delete them out of the box. Let’s see, how we can do the same programmatically, using JavaScript Object Model.

Internal Implementation

Scope of the article is,

  • Create a new list view.
  • Delete an existing view.
  • List all the views.

All of these operations will be done, using JavaScript object model.

Create a List View

  • Add the reference to jQuery file.
    1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    2. <script language="javascript" type="text/javascript">  
  • Within Document ready function, call SP.SOD.executeFunc, so as to load the on demand script SP.js . Call the main starting point function say: ‘createListView’,
    1. SP.SOD.executeFunc('sp.js''SP.ClientContext', createListView);  
  • Instantiate the client context, Web and list instance.
    1. //Get client context,web and list object   
    2. var clientContext = new SP.ClientContext();   
    3. var oWebsite = clientContext.get_web();   
    4. var oList = oWebsite.get_lists().getByTitle('Products');   
  • Create the view by instantiating ‘ViewCreationInformation’ object.
    1. //Create view using ViewCreationInformation object   
    2. var creationInfo = new SP.ViewCreationInformation();   
    3. creationInfo.set_title("CustomProductView");  
    4. creationInfo.set_setAsDefaultView("true");  
    5. creationInfo.set_rowLimit("10");  
    6. creationInfo.set_personalView("false");  
    7. creationInfo.set_viewFields(viewFields);  
  • Set CAML query, so that the view shows only the required subset of the items in the list.
    1. var camlQuery = new SP.CamlQuery();   
    2. var query = "<Where><IsNotNull><FieldRef Name='Product_x0020_Name' /></IsNotNull></Where>";   
    3. camlQuery.set_viewXml(query);   
    4. creationInfo.set_query(camlQuery);   
    5. oListViews=oList.get_views().add(creationInfo); 
  • Load the client context and execute the batch. 
    1. clientContext.load(oListViews);   
    2. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  

Output

Output

Full Code: The full code of the view creation is shown below:

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2. <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         SP.SOD.executeFunc('sp.js''SP.ClientContext', createListView);  
  5.     });  
  6.     var oListViews;  
  7.   
  8.     function createListView() {  
  9.         //Get client context,web and list object   
  10.         var clientContext = new SP.ClientContext();  
  11.         var oWebsite = clientContext.get_web();  
  12.         var oList = oWebsite.get_lists().getByTitle('Products');  
  13.         //Set the view fields  
  14.         var viewFields = new Array('Total_x0020_Sales''Sales_x0020_Target''Product_x0020_Name');  
  15.         var viewType = new SP.ViewType();  
  16.         //Create view using ViewCreationInformation object   
  17.         var creationInfo = new SP.ViewCreationInformation();  
  18.         creationInfo.set_title("CustomProductView");  
  19.         creationInfo.set_setAsDefaultView("true");  
  20.         creationInfo.set_rowLimit("10");  
  21.         creationInfo.set_personalView("false");  
  22.         creationInfo.set_viewFields(viewFields);  
  23.         //Set CAML query so that the view shows only a subset of items  
  24.         var camlQuery = new SP.CamlQuery();  
  25.         var query = "<Where><IsNotNull><FieldRef Name='Product_x0020_Name' /></IsNotNull></Where>";  
  26.         camlQuery.set_viewXml(query);  
  27.         creationInfo.set_query(camlQuery);  
  28.         oListViews = oList.get_views().add(creationInfo);  
  29.         //Load the client context and execute the batch   
  30.         clientContext.load(oListViews);  
  31.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  32.     }  
  33.   
  34.     function QuerySuccess() {  
  35.         console.log("Views created successfully!");  
  36.     }  
  37.   
  38.     function QueryFailure(sender, args) {  
  39.         console.log('Request failed' + args.get_message());  
  40.     }  
  41. </script>  
Delete List View

Similar to the view creation, we can implement deletion, using JSOM, as described below:

 

  • Add the reference to jQuery file.
    1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    2. <script language="javascript" type="text/javascript">  
  • Within Document ready function, call SP.SOD.executeFunc, so as to load the on demand script SP.js. Call the main starting point function say: ‘deleteListView’.
    1. SP.SOD.executeFunc('sp.js''SP.ClientContext',deleteListView);  
  • Instantiate the client context, web and list instance.
    1. //Get client context,web and list object   
    2. var clientContext = new SP.ClientContext();   
    3. var oWebsite = clientContext.get_web();   
    4. var oList = oWebsite.get_lists().getByTitle('Products');   
  • Get the view object to delete. 
    1. var oView = oList.get_views().getByTitle('CustomProductView');   
    2. view.deleteObject();  
  • Load the client context and execute the batch.
    1. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  

Output

Console Output is given below:

Console Output

Full Code: The full code for the view deletion is shown below:

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2. <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         SP.SOD.executeFunc('sp.js''SP.ClientContext', deleteListView);  
  5.     });  
  6.   
  7.     function deleteListView() {  
  8.         //Get the client context,web and list object   
  9.         var clientContext = new SP.ClientContext();  
  10.         var oWeb = clientContext.get_web();  
  11.         var oList = oWeb.get_lists().getByTitle('Products');  
  12.         //Get the view object to delete   
  13.         var oView = oList.get_views().getByTitle('CustomProductView');  
  14.         oView.deleteObject();  
  15.         //Execute the batch   
  16.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  17.     }  
  18.   
  19.     function QuerySuccess() {  
  20.         console.log('Specified View has been deleted.');  
  21.     }  
  22.   
  23.     function QueryFailure(sender, args) {  
  24.         console.log('Request failed' + args.get_message());  
  25.     }  
  26. </script>  
Get All Views

Just like the view creation and deletion, we can also get the list of all the views,  present within the list, using the script, given below. ‘oList.get_views()’ gets a collection of all the views, which are present within the list, which can be iterated upon by creating an enumerator collection, as shown in the code, given below:
  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2. <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         SP.SOD.executeFunc('sp.js''SP.ClientContext', getListViews);  
  5.     });  
  6.     var oListViews;  
  7.   
  8.     function getListViews() {  
  9.         //Get the client context,web and list object   
  10.         var clientContext = new SP.ClientContext();  
  11.         var oWeb = clientContext.get_web();  
  12.         var oList = oWeb.get_lists().getByTitle('Products');  
  13.         //Get the list view and load it to client context and execute the batch   
  14.         oListViews = oList.get_views();  
  15.         clientContext.load(oListViews);  
  16.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  17.     }  
  18.   
  19.     function QuerySuccess() {  
  20.         //Get the enumerator collection of list view and loop through it   
  21.         var enumerator = oListViews.getEnumerator();  
  22.         console.log("The available list views are: ");  
  23.         while (enumerator.moveNext()) {  
  24.             console.log(enumerator.get_current().get_title() + '\n');  
  25.         }  
  26.     }  
  27.   
  28.     function QueryFailure() {  
  29.         console.log('Request failed' + args.get_message());  
  30.     }  
  31. </script>  
Let’s see, how we can implement it in SharePoint. Save the scripts, given above, to a text file and upload it to Site Assets library.

SharePoint Implementation

 

  • Go to the edit settings of SharePoint page and click Web part from Insert tab.

    Web part

  • Add Content Editor Web part.

    Content Editor Web part

  • Click Edit Web art from Content Edit Web part. Assign the URL of the script text file and click Apply.

    Content Edit

Output

Output

Summary

Thus, we have seen, how to list out all the views, create a new view and delete an existing view, using JavaScript Object Model. This has been tried and tested in both SharePoint 2016 and Office 365.

Up Next
    Ebook Download
    View all
    Learn
    View all