Monday, August 7, 2017

Get a user from a Person field and check if they are in a SharePoint group

If you have a Person field (people picker) in your SharePoint form, and need to get that value, check if they're in a group, and take an action based on that, you can use the following:

<script type="text/javascript">

function IsCurrentUserMemberOfGroup(groupName, pickerTitle, OnComplete) {

// get people picker
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[$('[title="' + pickerTitle + '"]')[0].id];

// get the user dictionary
    var users = peoplePicker.GetAllUserInfo();
    // get the user name
   var currentUserAccountName = users[0]['Key'];
      // get current context and web
      var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();
        // get the user object
        var user = currentWeb.ensureUser(currentUserAccountName);
        // execute call to get user id
        Function.createDelegate(null, OnUserSuccess), 
        Function.createDelegate(null, OnUserFailure)

var groupUsers;

// Once we have the user, check if they're in the group
function OnUserSuccess(sender, args) {

// get all groups
var allGroups = currentWeb.get_siteGroups();

// get the group we're looking for
       var group = allGroups.getByName(groupName);

// get the users of the group
       groupUsers = group.get_users();


// loop through all users in the group and look for our user
        function OnGroupSuccess(sender, args) {
            var userInGroup = false;
            var groupUserEnumerator = groupUsers.getEnumerator();
            while (groupUserEnumerator.moveNext()) {
                var groupUser = groupUserEnumerator.get_current();
                if (groupUser.get_id() == user.get_id()) {
                    userInGroup = true;
        function OnUserFailure(sender, args) {

        function OnGroupFailure(sender, args) {

function IsCurrentUserHasContribPerms() 
  IsCurrentUserMemberOfGroup("Leadership Team", "Nominee", function (isCurrentUserInGroup) {
        alert('Leadership Team Members are not eligible to be nominated');
        $("input[value$='Save']").attr('disabled', true);
    else {
    $("input[value$='Save']").attr('disabled', false); 

function SetOnChangeEvent() 


ExecuteOrDelayUntilScriptLoaded(SetOnChangeEvent, 'SP.js');


No comments: