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?

  • 1
    The people picker field can be restricted to a group in the field's settings. Will this not work? – wjervis May 10 '17 at 11:01
up vote 3 down vote accepted

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. – wjervis May 10 '17 at 12:43
  • Updated the code as mention – Sunil Sahu May 10 '17 at 13:08
  • 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 – wjervis May 10 '17 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.

enter image description here

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.