Showing posts with label Views. Show all posts
Showing posts with label Views. Show all posts

Monday 23 May 2016

Create, Retrieve, Update Or Delete List Views Using CSOM with PowerShell On SharePoint Online


In this article, you will learn how we can retrieve, create, update or delete list views using CSOM with PowerShell. This is mainly focused on using PowerShell scripts for SharePoint online sites.

Get Views:


First we will see how we can get the existing views available on the SharePoint site. The steps followed here are very similar to the steps following CSOM or JSOM programming.
  1. Initialize context object with the site URL parameterThen initialize the SP Online Credentials with the above parameters and set it to the context.
  2. Then access the list using the context and then the views from the list, load the objects and execute the query.
  3. Loop through the result object and get the necessary view information.
    1. $siteURL = ""  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
    6. $ctx.credentials = $creds  
    7. try{  
    8.     $list = $ctx.web.Lists.GetByTitle("TestList")  
    9.     $views = $list.views  
    10.     $ctx.load($views)  
    11.     $ctx.executeQuery()  
    12.     foreach($view in $views){  
    13.         write-host $view.Title  
    14.     }  
    15. }  
    16. catch{  
    17.     write-host "$($_.Exception.Message)" -foregroundcolor red  
    18. }  
This will get all the view names available for the list on the site. Next, we will see how we can get one particular list on the site. 

Get View:

The operations are similar as the above section. After getting the list views, get the particular view using GetByTitle method.
  1. $siteURL = ""  
  2. $userId = ""  
  3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
  4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
  5. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
  6. $ctx.credentials = $creds  
  7. try{  
  8.     $list = $ctx.web.Lists.GetByTitle("TestList")  
  9.     $view = $list.views.GetByTitle("CustomView")  
  10.     $ctx.load($view)  
  11.     $ctx.executeQuery()  
  12.     write-host $view.Title  
  13. }  
  14. catch{  
  15.     write-host "$($_.Exception.Message)" -foregroundcolor red  
  16. }  

Create View:


Here we will see how we can create a list view. The following steps depict the flow.
  1. Initialize context object with the site URL parameterThen initialize the SP Online Credentials with the above parameters and set it to the context.
  2. Initialize the ViewCreationInformation object.
  3. Set the required parameters for new view. The necessary parameters are view name, type and view fields.
  4. Add new view to the view collection. Then Load and execute the query.
    1. $siteURL = ""  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
    6. $ctx.credentials = $creds  
    7. try{  
    8.     $list = $ctx.web.Lists.GetByTitle("TestList1")  
    9.     $views = $list.views  
    10.     $viewInfo = New-Object Microsoft.SharePoint.Client.ViewCreationInformation  
    11.     $viewInfo.Title = "CustomView"  
    12.     $viewInfo.ViewTypeKind = [Microsoft.SharePoint.Client.ViewType]::None  
    13.     $viewInfo.ViewFields = @("ID""Title""Author")  
    14.     $view = $views.Add($viewInfo)  
    15.     $ctx.load($view)  
    16.     $ctx.executeQuery()  
    17.     write-host $view.Title  
    18. }  
    19. catch{  
    20.     write-host "$($_.Exception.Message)" -foregroundcolor red  
    21. }  
The view will be added to the list. You will now see the view name changes. The following shows you the snapshot.

Delete List View:



Here we will see how we can delete the list view. The following steps depict you the flow. 
  1. Initialize context object with the site URL parameterThen initialize the SP Online Credentials with the above parameters and set it to the context.
  2. Get the list using GetByTitle method and then get views. From the view collection, find out the view to be deleted using GetByTitle method.
  3. Then, remove the view using the delete object method.
  4. Using the context, execute the query.
    1. $siteURL = ""  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
    6. $ctx.credentials = $creds  
    7. try{  
    8.     $list = $ctx.web.Lists.GetByTitle("TestList")  
    9.     $views = $list.views  
    10.     $view = $views.GetByTitle("CustomView")  
    11.     $view.DeleteObject()  
    12.     $ctx.executeQuery()  
    13.     Write-Host "View Deleted"  
    14. }  
    15. catch{  
    16.     write-host "$($_.Exception.Message)" -foregroundcolor red  
    17. }  
The view will be deleted from the list.

Update List View:


Here we will see how we can update the list view. The following steps depict you the flow.
  1. Initialize context object with the site URL parameterThen initialize the SP Online Credentials with the above parameters and set it to the context.
  2. Get the list using GetByTitle method and then get views. From the view collection, find out the view to be updated using GetByTitle method.
  3. In my case, I am trying to add a field to the view (Update Operation). You can do your own custom operation with your custom logic here.
  4. Then, update the view using the update method.
  5. Using the context, execute the query.
    1. $siteURL = ""  
    2. $userId = ""  
    3. $pwd = Read-Host -Prompt "Enter password" -AsSecureString  
    4. $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)  
    5. $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)  
    6. $ctx.credentials = $creds  
    7. try{  
    8.     $list = $ctx.web.Lists.GetByTitle("TestList1")  
    9.     $views = $list.views  
    10.     $view = $views.GetByTitle("CustomView")  
    11.     $viewFields = $view.ViewFields  
    12.     $viewFields.Add("Created")      
    13.     $view.Update()  
    14.     $ctx.executeQuery()      
    15. }  
    16. catch{  
    17.     write-host "$($_.Exception.Message)" -foregroundcolor red  
    18. }  
The view will be updated.

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