I have a people picker column "Assigned person" . I need to check on PreSaveAction() that entered user/s belong to a SharePoint group "Project leaders" or not. Any suggestion how do I get this done using javascript?
2 Answers
You check by below code and call CheckCurrentUserMembership() on PreSaveAction()
function CheckCurrentUserMembership() {
var clientContext = new SP.ClientContext.get_current();
var allGroups = currentWeb.get_siteGroups();
clientContext.load(allGroups);
var group = allGroups.getByName("Project leaders");
clientContext.load(group);
var groupUsers = group.get_users();
clientContext.load(groupUsers);
//var currentUser = clientContext.get_web().get_siteUsers().getById(userID);
clientContext.load(currentUser);
var userGroups = currentUser.get_groups();
clientContext.load(userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded,OnQueryFailed);
}
function OnQuerySucceeded() {
var userInGroup = false;
var controlID = $("div[title='AssignedTo']").id;
var userID=SPClientPeoplePicker.SPClientPeoplePickerDict[controlID].GetAllUserInfo()[0].EntityData.SPUserID
var groupUserEnumerator = groupUsers.getEnumerator();
while (groupUserEnumerator.moveNext()) {
var groupUser = groupUserEnumerator.get_current();
if (groupUser.get_id() == userID) {
isMember = true;
alert('Is a member');
break;
}
}
}
function OnQueryFailed() {
OnResult(false);
}
-
Would be better to get the group needed to check against, and then check if it's members contains the selected users in the people picker, rather than getting the selected user(s) groups and checking if they include the group.– wjervisCommented May 10, 2017 at 12:43
-
-
Only other thing is that the question suggests that the people picker might be a multi-user people picker. Other than that, good code. +1– wjervisCommented May 10, 2017 at 14:13
There is also a no-code solution to this. You can restrict the people field to fetch values from a particular group only.