SharePoint 2010 Client side script to check if a user is in a SharePoint group

The following script looks in the SharePoint object model if the current users exists in the SharePoint group 'My Group Name'. If the user exists, then the button 'My Button' is hidden:

ExecuteOrDelayUntilScriptLoaded(disableControls, "sp.js");

function disableControls() {
    clientContext = new SP.ClientContext.get_current();
    currentUser = clientContext.get_web().get_currentUser();
    clientContext.load(currentUser);
    this.collGroup = clientContext.get_web().get_siteGroups();
    clientContext.load(collGroup);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    var groupEnumerator = collGroup.getEnumerator();
    while (groupEnumerator.moveNext()) {
        var oGroup = groupEnumerator.get_current();
        if (oGroup.get_title() == "My Group Name") {
            users = oGroup.get_users();
            clientContext.load(users);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededFoundGroup), Function.createDelegate(this, this.onQueryFailed));
        }
    }
}

function onQuerySucceededFoundGroup(sender, args) {
    if (users.get_count() > 0) {
        UserExistInGroup = false;
        for (var i = 0; i < users.get_count(); i++) {
            if (users.itemAt(i).get_loginName() == this.currentUser.get_loginName()) {
                UserExistInGroup = true;
                break;
            }
        }
        if (UserExistInGroup) {
            $(':submit').each(function () { if ($(this).val() == "My Button") { $(this).hide(); } });
        }
    }
}

function onQueryFailed(sender, args) { }

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

CISM Exam Prep - Recommended Learning