Based on the below thread
https://social.msdn.microsoft.com/Forums/office/en-US/ac93c698-a2ab-4955-b1c1-48f1776b97e4/fetch-clientside-people-picker-multi-user-values-and-insert-into-custom-sp-group-programmatically?forum=onlineservicessharepoint
Below is the scenario:
1) Load the people picker field from SPGroup, when my splist's newform.aspx page is loaded
2) Bind the ppl picker field with the values from SPGroup
3) Now, when i simply click on save button, the members selected in the ppl picker control should be saved in the SPGroup ( jsom??)
4) strange thing happened, when i dont remove one person from ppl picker or if i dont add a new person in the people picker field and save button click :
The members from the group were GOT DELETED!! :-( --- > its Empty
Still didnt get why this happened! may be there is some conflict with asynchronous call??.
5) now, another test case:
i have added new members (say user10, user11) , in the pplpicker , after removing everyone from the existing ppl picker.
its worked without any issues. user10, user11 are added successfully in the spgroup.
am stuck at , why the initial case didnt work!!
the procedure am following is:
1) When user clicks on the Save Button:
am deleting all the members from spgroup as an initial step
then am fetching the values from people picker field, using user[i].key -->loginname values
and these values are going to be inserted into the spgroup.
this is the process, am following.
The issue is, when already some existing user is available in the group and hence binded with people picker field and when I retain them and clicked on Save button the group became empty!!
how to resolve this !!
help is appreciated!
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script><script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script><script type="text/javascript">
$(document).ready(function ()
{
GetUserFromGroup();
});
function GetUserFromGroup() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getbyname('QATESTGROUP')/users";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request)
{
//alert(data.d.results);
//console.log(data.d.results);
for(var i=0;i<data.d.results.length;i++)
{
var loginName = data.d.results[i].LoginName.split('|')[2];
doSetTimeout("pplpickerField",loginName);
}
}
function doSetTimeout(fieldName,LoginName)
{
//alert('field -- ppl picker');
setTimeout(function() { SetAndResolvePeoplePicker(fieldName, LoginName); }, 100);
}
function QueryError(error)
{
alert(error);
}
function SetAndResolvePeoplePicker(fieldName,LoginName)
{
var controlName = fieldName;
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
peoplePickerEditor.val(LoginName);
//alert(spPeoplePicker + ' --- is the sppeeople picker');
spPeoplePicker.AddUnresolvedUserFromEditor(true);
}
// Query the picker for user information.
// PeoplepickerId = Id of the people picker
function getUserInfo(PeoplepickerId) {
// Get the people picker object from the page.
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[PeoplepickerId + "_TopSpan"];
if (!peoplePicker.IsEmpty()) {
if (peoplePicker.HasInputError) return false; // if any error
else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
else if (peoplePicker.TotalUserCount > 0) {
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
var promise = '';
for (var i = 0; i < users.length; i++) {
UsersID += GetUserID(users[i].Key);
}
return UsersID;
}
} else {
return UsersID;
}
}
// Get the user ID.
function GetUserID(logonName) {
var item = {
'logonName': logonName
};
var UserId = $.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/ensureuser",
type: "POST",
async: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
return data.Id + ';#' + data.Title + ';#';
},
error: function(data) {
failure(data);
}
});
return UserId.responseJSON.d.Id + ';#' + UserId.responseJSON.d.Title + ';#';
}
function PreSaveAction()
{
//alert(' inside presaveaction ');
/////////////////////////////////// FIRST GET GROUP USERS and CALL DELETEUSER function ////////////////
//alert('going to get the getgroupusers');
var groupName="QATESTGROUP";
getGroupUsers("/_api/web/sitegroups/getbyname('"+groupName+"')/users?$select=Email").done(function(data){
data.d.results.forEach(function(user){
var email = user.Email;
//alert('one user email is ...'+ email);
deleteUser("/_api/web/sitegroups/getbyname('"+groupName+"')/users/getbyemail('"+email+"')").done(function(d_data){
// alert('deleted user' + email);
console.log(JSON.stringify(d_data));
});
});
});
//alert(' all users been deleted ');
//alert('starting of check== false');
//////////////////////////////////////////////////////////////////////////////////////////////////////
/*var check = false;
var controlName = 'Delegates';
// Get the people picker object from the page.
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
if (!peoplePicker.IsEmpty()) {
if (peoplePicker.HasInputError) return false; // if any error
else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
else if (peoplePicker.TotalUserCount > 0) {
//alert('get information about all users -- inside ppl picker count ');
//alert(peoplePicker.TotalUserCount + ' --- is the ppl picker usercount');
var users = peoplePicker.GetAllUserInfo();
for (var i = 0; i < users.length; i++) {
console.log(users[i].Key);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(2116)/users";
// alert('going to add the users into group');
$.ajax({
url: requestUri,
type: "POST",
async: false,
data: JSON.stringify({ '__metadata': { 'type': 'SP.User' }, 'LoginName': '' + users[i].Key + '' }),
headers: {"accept": "application/json;odata=verbose","content-type": "application/json;odata=verbose","X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
console.log('User Added');
check = true;
},
error: function (error) {
console.log(JSON.stringify(error));
check = false;
}
});
}
}
} else {
console.log('No user');
}
return check;*/
return true;
}
function getGroupUsers(url){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "GET",
headers: {"accept": "application/json;odata=verbose",
}
});
}
//Delete user
function deleteUser(url) {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
method: "POST",
headers: {"accept": "application/json;odata=verbose","X-RequestDigest": $("#__REQUESTDIGEST").val(),"IF-MATCH": "*","X-HTTP-Method": "DELETE"
}
});
}</script>