PeoplePicker Intialization, Saving Peoplepicker Value To The List, Setting Peoplepicker Value From The List

In this article, you will learn about PeoplePicker Intialization, saving Peoplepicker value to the list, and setting peoplepicker value from the list.

Develop SharePoint Framework Web Part.
 
Open a command prompt. Create a directory for SPFx solution.
 
md spfx-pnp-PeoplePicker
 
Navigate to the above created directory.
 
cd sspfx-pnp-PeoplePicker
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have default name (spfx-pnpExcel in this case) or type in any other name for your solution.
 
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
 
Selected choice: SharePoint Online only (latest)
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
 
Selected choice: Same folder
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and will be accessible everywhere.
 
Selected choice: N (install on each site explicitly)
 
Permissions to access web APIs
 
Choose if the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant.
 
Selected choice: N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose web part option.
 
Selected choice: WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
 
Selected choice: PnpPeoplePicker
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
 
Selected choice: React
 
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running below command.
 
npm shrinkwrap
 
In the command prompt, type below command to open the solution in the code editor of your choice.
 
code .
 
NPM Packages Used,
 
On the command prompt, run below command.
 
npm i @pnp/logging @pnp/common @pnp/odata @pnp/sp --save
npm install --save @pnp/polyfill-ie11
npm install @pnp/spfx-controls-react --save --save-exact 
 
In PnpPeoplePickerWebPart.ts
  1. import * as strings from 'PnpPeoplePickerWebPartStrings';  
  2. import PnpPeoplePicker from './components/PnpPeoplePicker';  
  3. import { IPnpPeoplePickerProps } from './components/IPnpPeoplePickerProps';  
  4.   
  5. export interface IPnpPeoplePickerWebPartProps {  
  6.   description: string;  
  7. }  
  8. export default class PnpPeoplePickerWebPart extends BaseClientSideWebPart<IPnpPeoplePickerWebPartProps> {   
  9.   public render(): void {  
  10.     const element: React.ReactElement<IPnpPeoplePickerProps > = React.createElement(  
  11.       PnpPeoplePicker,  
  12.       {  
  13.         context: this.context    
  14.       }  
  15.     );  
  16.   
  17.     ReactDom.render(element, this.domElement);  
  18.   }  
  19.   protected onDispose(): void {  
  20.     ReactDom.unmountComponentAtNode(this.domElement);  
  21.   }  
  22.   
  23.   protected get dataVersion(): Version {  
  24.     return Version.parse('1.0');  
  25.   }  
  26.   
  27.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  28.     return {  
  29.       pages: [  
  30.         {  
  31.           header: {  
  32.             description: strings.PropertyPaneDescription  
  33.           },  
  34.           groups: [  
  35.             {  
  36.               groupName: strings.BasicGroupName,  
  37.               groupFields: [  
  38.                 PropertyPaneTextField('description', {  
  39.                   label: strings.DescriptionFieldLabel  
  40.                 })  
  41.               ]  
  42.             }  
  43.           ]  
  44.         }  
  45.       ]  
  46.     };  
  47.   }  
  48. }  
in PnpPeoplePicker.tsx
  1. import { IPnPPeoplePickerState } from './IPnPPeoplePickerState';  
  2. import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";  
  3. import "@pnp/polyfill-ie11";  
  4. import { autobind ,DefaultButton} from 'office-ui-fabric-react';  
  5. import { sp, Web } from '@pnp/sp';   
  6. var managerlistid: number;  
  7. export default class PnpPeoplePicker extends React.Component<IPnpPeoplePickerProps, IPnPPeoplePickerState> {  
  8.   constructor(props: IPnpPeoplePickerProps, state: IPnPPeoplePickerState) {  
  9.     super(props);  
  10.     this.state = {  
  11.       addUsers: [],  
  12.       defaultmyusers: []  
  13.     };  
  14.     this.fetchdatas = this.fetchdatas.bind(this);  
  15.       this.fetchdatas();  
  16.   }  
  17.  private async fetchdatas() {  
  18.     const web = new Web(this.props.context.pageContext.web.absoluteUrl);  
  19.     const list1 = web.lists.getByTitle("Program");  
  20.     var myemail = [];  
  21.     var mynewid = [];  
  22.     var FetchProjectDetails = [];  
  23.     await list1.items.getById(1).select('Id,Mast/Id,Mast/Title,Mast/Name,Mast/EMail').expand('Mast').get().then(r => {  
  24.       console.log(r);  
  25.       managerlistid = r.Id;  
  26.       for (let i = 0; i < r.Mast.length; i++) {  
  27.         myemail.push(r.Mast[i].EMail);  
  28.         mynewid.push({  
  29.           id: r.Mast[i].Id,  
  30.           managername: r.Mast[i].Name  
  31.         });  
  32.       }  
  33.       this.setState({ defaultmyusers: myemail });  
  34.     });  
  35.   }  
  36.   public render(): React.ReactElement<IPnpPeoplePickerProps> {  
  37.     return (  
  38.       <div>  
  39.         <div id="Mast">  
  40.         <PeoplePicker  
  41.           context={this.props.context}  
  42.           titleText="Mast"  
  43.           personSelectionLimit={3}  
  44.           groupName={""// Leave this blank in case you want to filter from all users      
  45.           showtooltip={true}  
  46.           isRequired={true}  
  47.           disabled={false}  
  48.           ensureUser={true}  
  49.           showHiddenInUI={false}  
  50.           principalTypes={[PrincipalType.User]}  
  51.           defaultSelectedUsers={this.state.defaultmyusers}  
  52.           resolveDelay={1000} />  
  53.       </div>  
  54.       <div id="Client">  
  55.         <PeoplePicker  
  56.           context={this.props.context}  
  57.           titleText="Client"  
  58.           personSelectionLimit={3}  
  59.           groupName={""// Leave this blank in case you want to filter from all users      
  60.           showtooltip={true}  
  61.           isRequired={true}  
  62.           disabled={false}  
  63.           ensureUser={true}  
  64.           showHiddenInUI={false}  
  65.           principalTypes={[PrincipalType.User]}  
  66.           selectedItems={this._getPeoplePickerclient.bind(this)}  
  67.           resolveDelay={1000} />  
  68.           <DefaultButton  
  69.         data-automation-id="addSelectedUsers"  
  70.         title="Add Selected Users"  
  71.         onClick={this.addSelectedUsers}>   
  72.         Add Project  
  73.       </DefaultButton>  
  74.       </div>  
  75.       </div>  
  76.     );  
  77.   }  
  78.   private _getPeoplePickerclient(items: any[]) {  
  79.     console.log('Items:', items);  
  80.     this.setState({ addUsers: items });  
  81.   }  
  82.   @autobind   
  83.   private addSelectedUsers(): void{  
  84.     var peoplepicarray = [];  
  85.     for (let i = 0; i < this.state.addUsers.length; i++) {  
  86.       peoplepicarray.push(this.state.addUsers[i]["id"]);  
  87.     }  
  88.     var Clientdata ={  
  89.       "ClientId": { "results": peoplepicarray }  
  90.     };  
  91.     sp.web.lists.getByTitle("Program").items.add(Clientdata).then(i => {  
  92.       console.log("done");  
  93.     });  
  94.   }  
  95. }  
IPnPPeoplePickerState.ts
  1. export interface IPnPPeoplePickerState {    
  2.     addUsers: string[];    
  3.     defaultmyusers?:any[];  
  4. }   
In IPnpPeoplePickerProps.ts
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';    
  2. export interface IPnpPeoplePickerProps {  
  3.   context: WebPartContext;   
  4. }  
Here, in the first Peoplepicker I have bound the values taken from the list (setting default value).
 
The second  peoplepicker is for initialization and saving peoplepicker values to the list.
 
My list name is program and I have 2 peoplepicker columns, namely Mast and Client, where I have to fetch Mast values from the list and bind in the first peoplepicker 
 
In the second peoplepicker by clicking addSelectedUsers button the values are stored in the client column of the list where I have entered users. 
 
Happy Coding :)