4

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
  • 1
    The people picker field can be restricted to a group in the field's settings. Will this not work?
    – wjervis
    Commented May 10, 2017 at 11:01

2 Answers 2

3

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);
 }
3
  • 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
    Commented May 10, 2017 at 12:43
  • Updated the code as mention
    – Sunil Sahu
    Commented May 10, 2017 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
    Commented May 10, 2017 at 14:13
1

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

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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