2

How to get the user groups or roles for the current logged in user? I need to find this from the javascript/jquery. Is it possible ? I may get the current logged in user id from _spPageContextInfo.userId. Any thoughts on this ?

1

somone has already done most if not all the work for you ;) , its using the javascript client object model so you can utilise the sharepoint library.

function IsCurrentUserMemberOfGroup(strGroupName, functionComplete) {

        //Setup Vars
        currentContext  = null;
        currentWeb  = null;
        allGroups   = null;
        leaderGroup     = null;
        currentUser     = null;
        groupUsers  = null;

        //Get an instance of the Client Content.
        currentContext = new SP.ClientContext.get_current();

        //Grab the client web object.
        currentWeb = currentContext.get_web();

        //Get the current user object
        currentUser = currentContext.get_web().get_currentUser();
        currentContext.load(currentUser);

        //Setup the groupColletion.
        allGroups = currentWeb.get_siteGroups();
        currentContext.load(allGroups);

        //Now populate the objects above.
        currentContext.executeQueryAsync(
            Function.createDelegate(this, GetAllGroupsExecuteOnSuccess),
            Function.createDelegate(this, ExecuteOnFailure)
        );

        // GroupCollection - Load - SUCCESS
        function GetAllGroupsExecuteOnSuccess(sender, args) {

            // CHECK THE GROUPS
            // Time to Enumerate through the group collection that was returned.
            var groupEnumerator = allGroups.getEnumerator();

            // Loop for the collection.
            while (groupEnumerator.moveNext()) {

                //Grab the Group Item.
                var group = groupEnumerator.get_current();
                if (group.get_title().indexOf(strGroupName) > -1) {

                    // Now that we have the group let's grab the list of users.
                    groupUsers = group.get_users();
                    currentContext.load(groupUsers);
                    currentContext.executeQueryAsync(
                        Function.createDelegate(this, SingleGroupExecuteOnSuccess),
                        Function.createDelegate(this, ExecuteOnFailure)
                    );
                }
            }
        }

        // Single Group - Load - SUCCESS
        function SingleGroupExecuteOnSuccess(sender, args) {

            // Time to setup the Enumerator
            var groupUserEnumerator = groupUsers.getEnumerator();

            // This is the flag to set to true if the user is in the group.
            var boolUserInGroup = false;

            // and start looping.
            while (groupUserEnumerator.moveNext()) {

                //Grab the User Item.
                var groupUser = groupUserEnumerator.get_current();

                // and finally. If a Group User ID Matches the current user ID then they are in the group!
                if (groupUser.get_id() == currentUser.get_id()) {
                    boolUserInGroup = true;
                }
            }

            //Run the delegate function with the bool;
            functionComplete(boolUserInGroup);
        }

        // GroupCollection or Single Group - Load - FAILURE
        function ExecuteOnFailure(sender, args) {
            //Run the delegate function and return false because there was no match.
            functionComplete(false);
        }
 }

http://styledpoint.com/blog/sharepoint-2010-check-to-see-if-user-exists-in-a-group-via-javascript-ecma/

looks like you need to get the object more than once!

16
  • Thanks for the reply. I want the all the role Id's or group names assigned for the current user. How can I get that using this ? – Anish V Jan 31 '14 at 9:01
  • just ammended answer – Ali Jafer Jan 31 '14 at 9:31
  • I'm not getting the getEnumerator method for groups. Getting error! ""groups.getEnumerator(); The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. Error"" – Anish V Jan 31 '14 at 10:31
  • 1
    yes you do, thats what its complaining about! – Ali Jafer Feb 4 '14 at 14:12
  • 1
    just ammended my answer! iv ammended the code! this is one version and should work properly.... i dont really have the time to go through the other code but it has todo with loading the users into the group or user object and then iterating throug it..clientContext.Load(collGroup, groups => groups.Include( group => group.Users)); msdn.microsoft.com/en-us/library/office/… – Ali Jafer Feb 4 '14 at 15:02
2

At least two options are available to find a groups of which the specified user is a member

How to retrieve groups of which the specified user is a member via CSOM

The specified function returns the collection of groups of which the specified user is a member:

function GetGroupCollectionFromCurrentUser(OnSuccess,OnError) {

    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    var currentUser = web.get_currentUser();
    var groups = currentUser.get_groups();

    context.load(groups);
    context.executeQueryAsync(function(){
      OnSuccess(groups)
    },
    OnError);        
}

Example:

//Print groups for a current user
GetGroupCollectionFromCurrentUser(function(groups){
    var e = groups.getEnumerator();
    while (e.moveNext()) {
       var group = e.get_current();
       console.log(group.get_title());               
    }
  },
  function(sender,args){
    console.log('An error occured:' + args.get_message());
  }
);

How to retrieve groups of which the specified user is a member via UserGroup SOAP service

UserGroup.GetGroupCollectionFromUser Method Returns information about the collection of groups of which the specified user is a member

Example (SPServices is used here):

function getGroupsForCurrentUser()
{
  $().SPServices({
      operation: "GetGroupCollectionFromUser",
      userLoginName: $().SPServices.SPGetCurrentUser({ webURL: _spPageContextInfo.webAbsoluteUrl }),
      async: false,
      completefunc: function(xData, Status) {
        //Process xData.responseXML goes here...
      }
  });

Please follow SPServices documentation for a more details

3
  • Thanks for your detailed reply. I'm trying the first method. But, I'm not getting any groups!! Hence, I have checked the currentUser. Its also showing one error message if I try to get the currentUser.get_loginName(). The error message is as follows: The property or field 'LoginName' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. – Anish V Feb 3 '14 at 5:26
  • "var groups = currentUser.get_groups(); " is not working for me. Its seems an object is returning, but its not entering in the while loop. – Anish V Feb 3 '14 at 7:01
  • Hi, could you please clarify how the function GetGroupCollectionFromCurrentUser is called in your case? – Vadim Gremyachev Feb 4 '14 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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