In this blog, the method to add, update and delete SharePoint list view in SPFX application customizer is explained in-depth. We will see how we can use PnP in SPFX to perform all these ListView operations.
In the following code, we will go through the step-by-step method to add our custom views with required properties, update an existing ListView, and finally, delete a ListView.
Before you start using the code attached, you have to first install PnP using the command “npm install sp-pnp-js –save”.
The code block for this is mentioned below.
- import { override } from '@microsoft/decorators';
- import { Log } from '@microsoft/sp-core-library';
- import {BaseApplicationCustomizer} from '@microsoft/sp-application-base';
- import { Dialog } from '@microsoft/sp-dialog';
- import pnp from 'sp-pnp-js';
- import * as strings from 'HelloWorldApplicationCustomizerStrings';
- const LOG_SOURCE: string = 'HelloWorldApplicationCustomizer';
-
-
-
-
-
- export interface IHelloWorldApplicationCustomizerProperties {
-
- testMessage: string;
- }
-
- export default class HelloWorldApplicationCustomizer
- extends BaseApplicationCustomizer < IHelloWorldApplicationCustomizerProperties > {
- @override
- public onInit(): Promise < void > {
- pnp.setup({
- spfxContext: this.context
- });
-
-
- pnp.sp.web.lists.getByTitle("MyList").views.add("MyCustomView", false, {
- RowLimit: 10,
- DefaultView: true,
- ViewQuery: " < OrderBy > < FieldRef Name = 'Modified'
- Ascending = 'False' / > < /OrderBy>",
- }).then((v: ViewAddResult) => {
- v.view.fields.removeAll().then(_ => {
- Promise.all([
- v.view.fields.add("Title"),
- v.view.fields.add("Id"),
- v.view.fields.add("Modified"),
- ]).then(_ => {
- console.log("Custom listview created.");
- });
- });
- });
-
- pnp.sp.web.lists.getByTitle("MyList").views.getByTitle("MyCustomView").update({
- RowLimit: 20,
- }).then((v: ViewUpdateResult) => {
- console.log("Custom listview updated successfully.");
- });
-
- pnp.sp.web.lists.getByTitle("MyList").views.getByTitle("MyCustomView").delete().then(_ => {
- console.log("Custom listview deleted.");
- });
- return Promise.resolve();
- }
- }
After PnP is installed successfully, use the attached code in your SPFx solution to go through all SP ListView operations.