Forum Discussion

Carchambault's avatar
Carchambault
Copper Contributor
Sep 26, 2020

Sharepoint Framework Web Part filter list view

I have a new SPFx webpart working on my SPO workbench. I have it reading an internal list, but I want to limit the number of items that show in the web part. Specifically only the latest item. I have a "View" built on the list that limits the number of items to 1 and sorts it by created date so in my old (Classic) site it worked just fine, but now that I have to bulind a SPFx web part to get the design I want I can't get it to accept the views. I am trying this now: https://pnp.github.io/sp-dev-fx-property-controls/controls/PropertyFieldViewPicker/ and the filed works, but doesn't show my views. 

 

Thoughts?

  • Sudharsan K's avatar
    Sudharsan K
    Steel Contributor

    Carchambault what do you mean by the field works. You mean the field is displaying without any views in the web part properties window? if that is the case make sure you pass the correct listid to the field. Also, if you can share some code, it would be helpful for the community to provide a best solution.

     

    Hope it helps, please like it or mark it as a solution if it resolves your clarification or issue
    -Sudharsan K...

    • Carchambault's avatar
      Carchambault
      Copper Contributor

      Sudharsan K Thank you for your reply!

       

      Attached is my code and a screenshot of what is happening. Yes, I do believe I am missing the list ID, but have no idea where in the code it is not passing as the list information is there. 

       

      import { Version } from '@microsoft/sp-core-library';
      import { IPropertyPaneConfiguration } from '@microsoft/sp-property-pane';
      import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
      import { escape } from '@microsoft/sp-lodash-subset';
      import styles from './CeoCornerWebPart.module.scss';
      import * as strings from 'CeoCornerWebPartStrings';
      import { SPHttpClientSPHttpClientResponse } from '@microsoft/sp-http';
      import { EnvironmentEnvironmentType } from '@microsoft/sp-core-library';
      import { PropertyFieldViewPickerPropertyFieldViewPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldViewPicker';

      export interface ICeoCornerWebPartProps {
        liststring;
        viewsstring | string[];
      }
      export interface ISPLists 
      {
        valueISPList[];
      }

      export interface ISPList 
      {
        Titlestring;
      }

      export default class CeoCornerWebPart extends BaseClientSideWebPart<ICeoCornerWebPartProps> {

        private _getListData(): Promise<ISPLists>
        {
          return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "https://hcfhawaii.sharepoint.com/sites/Hookahi5/Lists/CEOCorner/Homepage.aspx",SPHttpClient.configurations.v1)
             .then((responseSPHttpClientResponse=> 
             {
             return response.json();
             });
         }
         private _renderListAsync(): void
         {
          if (Environment.type == EnvironmentType.SharePoint || 
                   Environment.type == EnvironmentType.ClassicSharePoint) {
           this._getListData()
             .then((response=> {
               this._renderList(response.value);
             });
      }

       }
         private _renderList(itemsISPList[]): void 
         {
          let htmlstring = '<div>';
          items.forEach((itemISPList=> {
            html += `
            <div>${item.Title}</div>
                `;
          });

          html += '</div>';

          const listContainerElement = this.domElement.querySelector('#spListContainer');
          listContainer.innerHTML = html;
        }

        public render(): void {
          this.domElement.innerHTML = `
            <div id="${ styles.ceocornerheader }">
             <div id="spListContainer" />
            </div>`;

            this._renderListAsync();
        }

        protected get dataVersion(): Version {
          return Version.parse('1.0');
        }

        protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
          return {
            pages: [
              {
                groups: [
                  {
                    groupFields: [
                        PropertyFieldViewPicker('view', {
                        label: 'Select a view',
                        listId: this.properties.list,
                        selectedView: this.properties.views,
                        orderBy: PropertyFieldViewPickerOrderBy.Title,
                        disabled: false,
                        onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
                        properties: this.properties,
                        context: this.context,
                        onGetErrorMessage: null,
                        deferredValidationTime: 0,
                        key: 'viewPickerFieldId'
                      })
                    ]
                  }
                ]
              }
            ]
          };
        }
      }

       

       

  • Sudharsan K's avatar
    Sudharsan K
    Steel Contributor

    Hi Carchambault,

    You are using SPFx web part with No Javascript Framework. The API URL you passed to retrieve the data is incorrect and please see the working copy of the code below. My list name is Area

    private _getListData(): Promise<any> {
    		let apiUrl: string = this.context.pageContext.web.absoluteUrl + `/_api/lists/getbytitle('Area')/items`;
    		return new Promise((res, rej) => {
    			this.context.spHttpClient.get(apiUrl, SPHttpClient.configurations.v1)
    				.then((respose: SPHttpClientResponse) => {
    					res(respose.json());
    				});
    		});
    	}

     Instead of using the default SPHttpClient, I recommend you to take a look at the PnP library. Below is the sample code using PnP library to fetch the same list data.

    private _getListDataUsingPnP() {
    		sp.web.lists.getByTitle('Area').items.select('Title').get()
    			.then(result => {
    				console.log("Using PnPJs: ", result);
    			});
    	}

    Using PnP library, the code would be clean and easy to read and understand by all the team members and there are more helpers available like select, filter, expand which I think is complicated implementing in the normal SPHttpClient option.

    Both the method returned the same results

    Take a look at it and let me know if you have any clarifications.

    Happy Coding...

     

    Hope it helps, please like it or mark it as a solution if it resolves your clarification or issue
    -Sudharsan K...

    • Carchambault's avatar
      Carchambault
      Copper Contributor

      Sudharsan K Thank you again. This is beginning to make more sense. Here is the copy of my current code. I think I am missing an authentication now? When I add your sample code I get an error on the 

       

      import { Version } from '@microsoft/sp-core-library';
      import { IPropertyPaneConfiguration } from '@microsoft/sp-property-pane';
      import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
      import { escape } from '@microsoft/sp-lodash-subset';
      import { PropertyFieldViewPickerPropertyFieldViewPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldViewPicker';
      import styles from './Ceo2WebPart.module.scss';
      import * as strings from 'Ceo2WebPartStrings';

      export interface ICeo2WebPartProps {
        descriptionstring;
        listsstring;
        viewsstring
      }

      export default class Ceo2WebPart extends BaseClientSideWebPart<ICeo2WebPartProps> {

        private _getListDataUsingPnP() {
          sp.web.lists.getByTitle('CEOCornera').items.select('Title').get()
            .then(result => {
              console.log("Using PnPJs: "result);
            });
        }

        public render(): void {
          this.domElement.innerHTML = `
            <div class="${ styles.ceo2 }">
              <div class="${ styles.container }">
                <div class="${ styles.row }">
                  <div class="${ styles.column }">
                    <span class="${ styles.title }">Welcome to SharePoint!</span>
                    <p class="${ styles.subTitle }">Customize SharePoint experiences using Web Parts.</p>
                    <p class="${ styles.description }">${escape(this.properties.description)}</p>
                    <a href="https://aka.ms/spfx" class="${ styles.button }">
                      <span class="${ styles.label }">Learn more</span>
                    </a>
                  </div>
                </div>
              </div>
            </div>`;
        }

        protected get dataVersion(): Version {
          return Version.parse('1.0');
        }

        protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {

          return {
              pages: [
                {
                  header: {
                    description: strings.PropertyPaneDescription
                  },
                  groups: [
                    {
                      groupName: strings.BasicGroupName,
                      groupFields: [
                      PropertyFieldViewPicker('views', {
                        label: 'Select a view',
                        listId: this.properties.lists,
                        selectedView: this.properties.views,
                        orderBy: PropertyFieldViewPickerOrderBy.Title,
                        disabled: false,
                        onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
                        properties: this.properties,
                        context: this.context,
                        onGetErrorMessage: null,
                        deferredValidationTime: 0,
                        key: 'viewPickerFieldId'
                      })
                      ]
                    }
                  ]
                }
              ]
            };
          }
      }
      • Sudharsan K's avatar
        Sudharsan K
        Steel Contributor

        Hi Carchambault 

        I am so sorry that I missed the code that had to be added to the imports before that have you installed the PnP npm package? if not use the below command to install it and add the import statement mentioned below. After that, your code should work without any errors.

        npm install @pnp/sp --save
        import { sp } from "@pnp/sp";

         

Resources