top of page
Writer's pictureNakkeeran Natarajan

Working With Cascading Dropdowns In SPFx Webpart Properties

Introduction

In this article, you will learn how to populate cascading dropdown options in SharePoint Framework (SPFx) web part properties pane.


In my SPFx article series, you can learn about SPFx introduction, prerequisites, steps for setting up the environment, developing, and testing the web parts, using the local environments.

The below articles will help you with basic SPFx web part properties pane customization.  

In my previous article, you have seen how to add and bind values dynamically to the dropdown field of web part property pane. In this article, you will see how to populate cascading dropdown fields with dynamic SharePoint list content. I have used two dropdowns in this sample.


Declare Drop down Fields/Properties

The dropdown values appended to the field is of type IPropertyPaneDropdownOption. The variables "listDropDownOptions" and "itemDropDownOptions" of same type are declared inside the class.

The below snippet shows the property declaration.

  1. private listDropDownOptions: IPropertyPaneDropdownOption[] =[];  

  2. private itemDropDownOptions: IPropertyPaneDropdownOption[] = [];  


Define Properties

The properties are defined using propertyPaneSettings() method. The below snippet shows the properties defined.

  1. protected get propertyPaneSettings(): IPropertyPaneSettings {  

  2. return {      pages: [        {          

  3. header: {            

  4. description: strings.PropertyPaneDescription,          

  5. },          

  6. groups: [            {              

  7. groupName:"Lists",              

  8. groupFields:

  9. [                

  10. PropertyPaneDropdown('listDropDown',

  11. {                  

  12. label: "Select List To Display on the page",                  

  13. options:this.listDropDownOptions,                  

  14. isDisabled: false               

  15. }),                

  16. PropertyPaneDropdown('ItemsDropDown',

  17. {                  

  18. label: "Select Item to display",                  

  19. options: this.itemDropDownOptions,                  

  20. isDisabled: false               

  21. })              

  22. ]            

  23. }          

  24. ]        

  25. }      

  26. ]    

  27. };  

  28. }  


Note - There are two properties defined. One dropdown is for list source and the other dropdown is for listing down the items of the list. As you can see, the values are not appended directly, rather variable of type IPropertyPaneDropdownOption is assigned. 


Load First Dropdown (List Dropdown)

Initially, on the property pane load, all the lists available in the SharePoint site should be listed in the list dropdown. Next, we need to load the list names on the dropdown field dynamically.

To load the values, onPropertyPaneConfigurationStart method is used. It loads only when the property pane is opened. So, this method will be used in the current sample.


Note - There is one more way of loading the dropdown values, explained in the previous article.

The below snippet shows the methods to load the list names into list dropdown. The custom function is written to load the SharePoint list names into the dropdown property. Here, this.listDropDownOptions property is loaded with the list names, which will reflect in the list dropdown property.

  1. protected onPropertyPaneConfigurationStart(): void {  

  2. // loads list name into list dropdown

  3. this.GetLists();  

  4. }  

  5. private GetLists():void{  

  6. // REST API to pull the list names   

  7. let listresturl: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists?

  8. $select=Id,Title";   this.LoadLists(listresturl).then((response)=>{  

  9. // Render the data in the web part

  10. this.LoadDropDownValues(response.value);    

  11. });  

  12. }  

  13. private LoadLists(listresturl:string): Promise<spLists>{  

  14. // Call to site to get the list names

  15. return this.context.httpClient.get(listresturl).then((response: Response)=>{  

  16. return response.json();    });  }  

  17. private LoadDropDownValues(lists: spList[]): void{    

  18. lists.forEach((list:spList)=>{  

  19. // Loads the drop down values

  20. this.listDropDownOptions.push({key:list.Title,text:list.Title});    

  21. });  

  22. }  

Load Second Dropdown (Items Dropdown)

Then, once the list name is selected, the items dropdown property should be populated. This can be done by overriding onPropertyChange method. The method takes two parameters (property path and new value). The function should be executed only when the list dropdown property is changed.


The below snippet shows the methods to load the items (item Title field) into list dropdown. The custom function is written to load the SharePoint item titles into the items dropdown property. Here, this.itemsDropDownOptions property is loaded with the item titles, which will reflect in the item dropdown property.

  1. protected onPropertyChange(propertyPath: string, newValue: any):void{  

  2. if(propertyPath === "listDropDown"){  

  3. // Change only when drop down changes

  4. super.onPropertyChange(propertyPath,newValue);  

  5. // Clears the existing data

  6. this.properties.ItemsDropDown = undefined;  

  7. this.onPropertyChange('ItemsDropDown', 

  8. this.properties.ItemsDropDown);  

  9. // Get/Load new items data this.GetItems();    

  10. }  

  11. else {  

  12. // Render the property field

  13. super.onPropertyChange(propertyPath, newValue);    

  14. }  

  15. }  

  16. private GetItems(): void{  

  17. // Retrives Items from SP List

  18. if(this.properties.listDropDown != undefined)

  19. {      

  20. let url: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('"+this.properties.listDropDown+"')/items?$select=ID,Title,Created,Author/Title&$expand=Author";  

  21. this.GetItemsDropDown(url).then((response)=>{  

  22. // Loads in to drop down field

  23. this.LoadItemsDropDown(response.value);      

  24. });    

  25. }  

  26. }  

  27. private GetItemsDropDown(listresturl:string): Promise<spListItems>{  

  28. // Call to list to get the items

  29. return this.context.httpClient.get(listresturl).then((response: Response)=>{  

  30. return response.json();    

  31. });  

  32. }  

  33. private LoadItemsDropDown(listitems: spListItem[]): void{  

  34. // Populates drop down values

  35. this.itemDropDownOptions = [];  

  36. if(listitems != undefined)

  37. {     

  38.  listitems.forEach((listItem:spListItem)=>{  

  39. this.itemDropDownOptions.push({key:listItem.ID,text:listItem.Title});      

  40. });    

  41. }  

  42. }  


Render Web Part

The data displayed on the web part is rendered using render method. The web part should be rendered based on the values selected from two dropdowns. The custom functions are written inside render() method to display the list items based on the list name and items selected from the dropdowns.


The below snippet shows the functions to render the data on the web part.

  1. public render(): void {  

  2. // Render the items in tabular format

  3. this.domElement.innerHTML = `      <div class="${styles.listItemsForm}">        

  4. <div class="${styles.Table}">          

  5. <div class="${styles.Heading}">            

  6. <div class="${styles.Cell}">Title</div>            

  7. <div class="${styles.Cell}">Created</div>            

  8. <div class="${styles.Cell}">Author</div>          

  9. </div>        

  10. </div>      

  11. </div>`;      

  12. console.log("Render");  

  13. this.LoadData();  

  14. }  

  15. private LoadData(): void{  

  16. if(this.properties.listDropDown != undefined && this.properties.ItemsDropDown != undefined){      

  17. let url: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('"+this.properties.listDropDown+"')/items?

  18. $select=Title,Created,Author/Title&$expand=Author&$filter=ID eq "+this.properties.ItemsDropDown;  

  19. this.GetListData(url).then((response)=>{  

  20. // Render the data in the web part

  21. this.RenderListData(response.value);      

  22. });    

  23. }  

  24. }  

  25. private GetListData(url: string): Promise<spListItems>{  

  26. // Retrieves data from SP list

  27. return this.context.httpClient.get(url).then((response: Response)=>{  

  28. return response.json();    

  29. });  

  30. }  

  31. private RenderListData(listItems: spListItem[]): void{    

  32. let itemsHtml: string = "";  

  33. // Displays the values in table rows   

  34. listItems.forEach((listItem: spListItem)=>{     

  35.  itemsHtml += `<div class="${styles.Row}">`;     

  36.  itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Title}</p></div>`;        

  37. itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Created}</p></div>`;       

  38.  itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Author.Title}</p></div>`;       

  39. itemsHtml += `</div>`;    

  40. });  

  41. this.domElement.querySelector("."+styles.Table).innerHTML +=itemsHtml;  

  42. }  

Interfaces

The interfaces required for the sample can be found below.

  1. export interface spListItems{    

  2. value: spListItem[];  

  3. }  

  4. export interface spListItem{    

  5. Title: string;    

  6. ID: string;    

  7. Created: string;    

  8. Author: {      

  9. Title: string;    

  10. };  

  11. }  

  12. export interface spList{  

  13. Title:string;  

  14. id: string;  

  15. }  

  16. export interface spLists{    

  17. value: spList[];  

  18. }  


The below snapshot shows the web part with the cascading dropdown fields on SPFx web part properties pane.



Summary 

Thus, you have learned how to build the cascading dropdown and populate the values dynamically on the SharePoint Framework web part properties pane. 

0 comments

Comments


bottom of page