Create a new VIEW in SharePoint List

In this article, we will cover how to use the PnP JS Core library to create a new view in SharePoint list. To know more about this JavaScript library, check the below links

In this post,

How to create new VIEW in SharePoint List using PnP JavaScript Library.

Syntax:

pnp.sp.web.lists.getByTitle(<ListName>).views.(
title: string, 
personalView = false, 
additionalSettings: TypedHash<string | number | boolean> = {}): Promise<ViewAddResult> 
Adds a new view to the SharePoint List based on the specified parameters
ListName - Title of the SharePoint List, where we want to add the view @param1 > title - The new views's title @param2 > personalView - True if this is a personal view, otherwise false, default = false @param3 > additionalSettings - Will be passed as part of the view creation body

Example:

The below steps and code snippets used to create a new view in SharePoint list using PnP JavaScript library,

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
    • Download pnp.js PnP JS file
    • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
    • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  2. Create new web part page and insert Content Editor web part
  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet

<script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>
<script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script> 
<script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>
  
<span id="sample"></span>

<script type="text/javascript">  
//The below views.add method creates the view and enables the mobile view & sets this view as a mobile default view
$pnp.sp.web.lists.getByTitle("List Title").views.add('View Name', false, {
    'MobileView': true,
    'MobileDefaultView': true
}).then(function(res) {
    document.getElementById("sample").innerHTML = res.data.Title + " - view created successfully";
});
</script>

Typescript Example:

Typescript is the superset of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript. The below is the typescript example for adding a new view to the SharePoint List.


import pnp from "sp-pnp-js";
 
pnp.sp.web.lists.getByTitle("List Title").views.add("View Name",false).then((res) =>{
    console.log(`${res.data.Title} created successfully`);
  }).catch(err=>{
    console.log(`Error: ${err}`)
  });
 

Output:

Our code returns the success message, if the view created successfully for the SharePoint List.

Leave a Reply

Your email address will not be published. Required fields are marked *