Friday 15 September 2017

SharePoint 2013 Client People Picker (Person or Group)

While developing custom forms using HTML/Angularjs we might need people picker controls as well in our HTML.

 Thanks to Microsoft, now in SharePoint we can use client people picker and which you can customize based on your requirement.

Below is the code which we are going to use in our SharePoint page.

I have only used in aspx page which inherits SharePoint master page, i tried in custom aspx page as well but i was not able to implement it.


HTML : 

<div id="ppRMName"></div>

You need below references to initialize it on your page.

<script src="/_layouts/15/clientforms.js"></script> <script src="/_layouts/15/clientpeoplepicker.js"></script>
<script src="/_layouts/15/autofill.js"></script>  
<script src="/_layouts/15/clienttemplates.js"></script>  
<script src="/_layouts/15/sp.js"></script>  
<script src="/_layouts/15/sp.runtime.js"></script>  



Javascript : 

 I used timeout because sometimes it was not loading in browser, you can try calling directly as well.

$(document).ready(function($scope) {
    $("#ppRMName").spPeoplePicker();   
});
$.fn.spPeoplePicker = function() {
    setTimeout(
        function() {          
            ExecuteOrDelayUntilScriptLoaded(function() {
                initializePeoplePicker("ppRMName");
            }, 'sp.core.js');

        }, 500);

}

// function to show people picker control on page, now we need to save and retrieve data as well from People picker
function initializePeoplePicker(peoplePickerElementId) {
// Create a schema to store picker properties, and set the properties.  
var schema = {};
//schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
schema['PrincipalAccountType'] = 'User';
//This value specifies where you would want to search for the valid values
schema['SearchPrincipalSource'] = 15;
//This value specifies where you would want to resolve for the valid values
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = false; // you can define single/multiple here
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '300px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}

// retrieve People picker values

var RMName =  getUserInfo_ppRMName();

function getUserInfo_ppRMName() {
// Get the people picker object from the page.
//ppRMName_TopSpan is the span id which is hard coded
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.ppRMName_TopSpan;

// Get information about all users.
var userName = getUserInfo(peoplePicker);
return userName;

}

function getUserInfo(peoplePicker) {

var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
var userName = '';
for (var i = 0; i < users.length; i++) {
var user = users[i];
for (var userProperty in user) {
userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
}
}
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
if (users.length > 0) {
userName = GetSPUserInfo(users[0].Key);

}
return userName;

}

// need spservice reference
function GetSPUserInfo(LoginName) {

var Data = {};
$().SPServices({
operation: "GetUserInfo",
async: false,
userLoginName: LoginName,
completefunc: function(xData, Status) {
$(xData.responseXML).find("User").each(function() {
Data.UserId = $(this).attr("ID");
Data.UserName = $(this).attr("Name");
Data.FullUserName = $(this).attr("ID") + ";#" + $(this).attr("Name");
});
}
});
//return Data;
if (Data.UserId) {
return Data.UserId;
} else {
return AddUsertoGroup(LoginName, "5");
               // if user is new to Sharepoint site, we need to add user to sharepoint to get the user id.
}
}
//This function might ask for authentication pop up, i fixed it using SPservice code to add user

function AddUsertoGroup(userLoginName, GroupID) {
var useridval = "";
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(" + GroupID + ")/users",
type: "POST",
async: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'__metadata': {
'type': 'SP.User'
},
'LoginName': userLoginName
}),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
useridval = data.d.Id;
},
error: function(data) {
console.log(data);
}
});
return useridval;
}


Now if you want to set people picker control : PopulatePeoplePicker_ppRMName("UserID");

function PopulatePeoplePicker_ppRMName(UserID) {
var divPeople = SPClientPeoplePicker.SPClientPeoplePickerDict.ppRMName_TopSpan;
var userObj = {
'Key': Value
};
divPeople.AddUnresolvedUser(userObj, true);
}

You want to clear or reset people picker control in some scenarios, below is the function for that.

clearPP("ppRMName_TopSpan");

function clearPP(ppid) {
var spclientPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppid];
if (spclientPeoplePicker) {
//Get the Resolved Users list from Client People Picker
var ResolvedUsers = $(document.getElementById(spclientPeoplePicker.ResolvedListElementId)).find("span[class='sp-peoplepicker-userSpan']");
//Clear the Client People Picker
$(ResolvedUsers).each(function(index) {
spclientPeoplePicker.DeleteProcessedUser(this);
});
}

}


1 comment:

  1. Titanium trim hair cutter and top cap - TITIAN ART
    Shop tatian ti 89 titanium calculator art for the titanium iv chloride perfect tatian trim beard for titanium tv alternative your new T-Shirt, T-Shirt and more. Get ready to make black titanium ring the thinkpad x1 titanium cut!

    ReplyDelete