In continuation with Part 1 where we created a Ribbon button. In this post we will look at the code for EnableIfUserInGroup() which will enable\disable the Ribbon button.
6. Next add a Javascript file in your project “CheckUserInGroup.js” and add it under Layouts -> RibbonScripts folder. Create Layouts folder using Add-> “Sharepoint Layouts Mapped Folder” .
7. Next, the following goes in your CheckUserInGroup.js file
<script src=”/_layouts/SP.js” type=”text/ecmascript”></script>
<script type=”text/javascript”>
// The below is called by EnabledScript in ribbon button
function EnableIfUserInGroup() {
var _userInGroup;
if (UserExistInGroup == null)
CheckUser();
else {
_userInGroup = UserExistInGroup;
UserExistInGroup = null;
return _userInGroup;
}
}
// The below checks if the user exists in the group
function CheckUser()
{
var clientContext = new SP.ClientContext();
var groupCollection = clientContext.get_web().get_siteGroups();
// Get the Our Group’s ID
var _group = groupCollection.getById(10); ->> ID of the Group that we are checking against e.g. ListOwners group
var users = _group.get_users(); ->> Get all Users of the group
clientContext.load(_group);
clientContext.load(users,’Include(loginName)’);
this._currentUser = clientContext.get_web().get_currentUser(); ->> Get current user
clientContext.load(this._currentUser,’Include(loginName)’);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
RefreshCommandUI(); ->> Refreshes the Ribbon again to pick up the new value for UserExistInGroup
}
//The below Checks if User is the member of the specified group
function onQuerySucceeded() {
if(users.count >0)
{
UserExistInGroup = false;
for(var i=0; i < users.count; i++)
{
if(users[i].get_loginName() == this._currentUser.get_loginName())
{
UserExistInGroup = true;
}
}
}}
function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
</script>
8. Next Build and deploy.





