Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link

I have copied some snippets of code from herehere

I have copied some snippets of code from here

I have copied some snippets of code from here

Source Link
Michael
  • 199
  • 4
  • 17

groups.getByName(groupname) is undefined

I have copied some snippets of code from here: http://stackoverflow.com/questions/22122139/check-if-current-users-belongs-to-sp-group-using-javascript-client-side-object-m

to test if a user belongs to a certain group, I am using Sharepoint 2010, however I am getting an method is undefined error.

I am making sure that sp.js is loaded with :

$(document).ready(function () {
    ExecuteOrDelayUntilScriptLoaded(removeLink, "sp.js");
});

then when this is loaded I check if the user is a current member:

    function removeLink(){
        IsCurrentUserMemberOfGroup("Approvers", function (isCurrentUserInGroup){
        if(isCurrentUserInGroup)
   {
    alert(isCurrentUserInGroup);
   }
   else
   {
       alert(isCurrentUserInGroup + "- no");
   }
        });

    }

The isCurrentUserMemberOfgroup method looks like this:

function IsCurrentUserMemberOfGroup(groupName, OnComplete) {

var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();

        var currentUser = currentContext.get_web().get_currentUser();
        currentContext.load(currentUser);

        var allGroups = currentWeb.get_siteGroups();
        currentContext.load(allGroups);

        var group = allGroups.getByName(groupName);   //ERROR HERE
        currentContext.load(group);

        var groupUsers = group.get_users();
        currentContext.load(groupUsers);

        currentContext.executeQueryAsync(OnSuccess,OnFailure);

        function OnSuccess(sender, args) {
            var userInGroup = false;
            var groupUserEnumerator = groupUsers.getEnumerator();
            while (groupUserEnumerator.moveNext()) {
                var groupUser = groupUserEnumerator.get_current();
                if (groupUser.get_id() == currentUser.get_id()) {
                    userInGroup = true;
                    break;
                }
            }  
            OnComplete(userInGroup);
        }

        function OnFailure(sender, args) {
            OnComplete(false);
        }    
}

However this line causes an error:

        var group = allGroups.getByName(groupName);   //ERROR HERE

allGroups is defined, however it contains no method getByName()