Introduction
In this blog, we will learn to set the default current logged in user to SharePoint OOTB people picker control on a page load using the SharePoint Framework (SPFx).
People picker is used to select one or more entities. Pickers are used to manage a group of people by selecting from the list of people within a group.
Steps Involved
Declare SPclientPeoplePicker as global variable in your .tsx file as shown below.
- declare var SPClientPeoplePicker: any;
Install Jquery and sp-pnp-js to your .tsx file as shown below.
- npm install --save sp-pnp-js
- npm install --save jquery
Import
sp-pnp-js and Jquery to your .tsx file as shown below.
- import * as pnp from "sp-pnp-js";
- import $ from "jquery";
The below function is used to retrieve current logged in user details:
-
- public async spLoggedInUserDetails(ctx: any): Promise<any>{
- try {
- const web = new pnp.Web(ctx.pageContext.site.absoluteUrl);
- return await web.currentUser.get();
- } catch (error) {
- console.log(`Error occured in spLoggedInUserDetails method - Error message: ${error.message}`);
- throw error;
- }
- }
Below function retrieves user email address and div id of the sharepoint OOTB people picker control and sends it as a parmeter to setSinglePeoplePicker to set current logged in user.
-
- private async setCurrentLoggedInUserPP(){
- try {
- let userDetails = await this.spLoggedInUserDetails(this.props.ctx);
- var loginName = userDetails.LoginName;
- var emailAddress = loginName.split("|")[2];
- var divID = $("div[title='people picker column title']").attr('id');
- this.setSinglePeoplePicker(divID,emailAddress);
- } catch (error) {
- console.log("Error in setCurrentLoggedInUserPP" + error);
- }
- }
Below function accepts DivId and EmailAddress as input parameters to set the values to people picker control.
divID - ID of the people picker control for which the default values to be inserted.
emailAddress - Email Address of the user.
-
- public setSinglePeoplePicker(divID, emailAddress): void {
- try {
- SPClientPeoplePicker.SPClientPeoplePickerDict[divID].AddUnresolvedUser({'Key':emailAddress},true);
- } catch (error) {
- console.log(`Error occured in setSinglePeoplePicker method - Error message: ${error.message}`);
- throw error;
- }
- }
Usage: Call the method in your componentDidMount Function.
- this.setCurrentLoggedInUserPP();
Please feel free to share your comments.
Hope this helps!!!!!