Get SPList column values in SPFX application customizer using PnP.

In this blog the method to get a SharePoint lists column values in SPFX application customizer is explained elaborately. We will see how we can use pnp in SPFX to get our required values.

In the following code we will retrieve the value of the default columns for example “Title”, “Id” etc. also value of some custom columns.

In the following code block I have retrieved following column values:

  1. Title
  2. Id
  3. MyCustomFld which is a custom column
  4. MyLookUpFld which is a custom column(Lookup column).

Befor 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';

/**
 * If your command set uses the ClientSideComponentProperties JSON input,
 * it will be deserialized into the BaseExtension.properties object.
 * You can define an interface to describe it.
 */
export interface IHelloWorldApplicationCustomizerProperties {
  // This is an example; replace with your own property
  testMessage: string;
}

/** A Custom Action which can be run during execution of a Client Side Application */
export default class HelloWorldApplicationCustomizer
  extends BaseApplicationCustomizer<IHelloWorldApplicationCustomizerProperties> {

    @override
    public onInit(): Promise<void> {
      pnp.setup({
        spfxContext: this.context
      });
  
      //Here "My List" is Sharepoint list title
      pnp.sp.web.lists.getByTitle("My List").items.select("Title", "Id", "MyCustomFld", "MyLookUpFld/ID").expand("MyLookUpFld").getPaged().then(p => {
                  
            console.log(JSON.stringify(p.results, null, 4));
            var itemColl = p.results;
            for (var index = 0; index < itemColl.length; index++) {
              var element = itemColl[index];
              var title = element["Title"];
              var id = element["Id"];
              var customFldValue = element["MyCustomFld"];
              var lookUpFld = element["MyLookUpFld"];
              var lookUpFldId = lookUpFld["ID"];
              console.log("Item with Id: " + id + " and title: " + title + " has MyCustomFld field value: " + customFldValue + " and MyLookUpFld lookup field value: " + lookUpFldId);
            }
      });
  
      return Promise.resolve();
    }
}

After PnP is installed successfully use the attached code in your SPFx solution to retrieve SPList column values.

Tags: ,

Leave a Reply

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