Monday, October 24, 2011

Sharepoint 2010 - Enable/Disable Ribbon Button with EcmaScript

I show you a detailed example of how to enable and disable a ribbon button according to the current user’s group.

The example uses “EnabledScript” attribute of the CommandUIHandler of the ribbon button.

Then the EnabledScript is built with EcmaScript to find groups and user info.

Lets Start with creating a Ribbon button first.
1. Create a empty project.
2. Deploy it as a Farm solution.
3. Right click on the feature and click “Add feature”.
4. Right click on the project and add a new “Empty Element” item.
5. Next add the below code to add a custom Ribbon button to your document library.

<Elements xmlns=”” >
Title=”Owners Group Button”>
<Button Id=”Ribbon.Library.ViewFormat.UsersBtn”
LabelText=”Group Users Button”
TemplateAlias=”o1″ />
EnabledScript=”javascript:EnablerScript('10,14');” -> Enable Ribbon function here
//Referencing the Script
ScriptSrc =”/_layouts/RibbonScripts/CheckUserInGroup.js”/>

The Group Users Button created in the above code will be in the disabled mode on page load. The code in EnablerScript('10,14'); will determine if the current  user is added to the specified group and the button needs to be enabled.
The CustomAction ScriptLink refers to the path of the CheckUserInGroup.js file which contains EnablerScript('10,14'); and other JavaScript functions.

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. The following goes in your CheckUserInGroup.js file
// The below is called by EnabledScript in ribbon button

var idGroupToVerify1 = 10;

var isGroupToVerify2 = 14;
var nameGroup1 = "nameGroup1";
var nameGroup2 = "nameGroup2";
var arrIsInThisGroup = new Array(2);
arrIsInThisGroup["nameGroup1"] = false;
arrIsInThisGroup["nameGroup2"] = false;

ExecuteOrDelayUntilScriptLoaded(InitGroups, "sp.js");
//initialize groups ids for the current user
function InitGroups() {
    CheckUser(idGroupToVerify1, nameGroup1);
   //beacuse of some errors if execute together
    setTimeout("CheckUser(" + idGroupToVerify2 + ", '" + nameGroup2 + "')", 500);

function EnablerScript(groupID) {
    if (groupID) {
        var isButtonEnabled = false;
    //groupid comes in string comma separated
   // '10' or '10,14'
        var arrGrId = groupID.split(',');
        var i = 0;
        for (i = 0; i < arrGrId.length; i++) {
            var currGroupID = arrGrId[i];
            if (currGroupID == idGroupToVerify1)
                isButtonEnabled = isButtonEnabled || arrIsInThisGroup[nameGroup1];
            if (currGroupID == idGroupToVerify2)
                isButtonEnabled = isButtonEnabled || arrIsInThisGroup[nameGroup2];
        return isButtonEnabled;
    return true;

// The below checks if the user exists in the group
function CheckUser(groupID, isInThisGroup) {

    var context = SP.ClientContext.get_current();
   //I go to parent site if I'm in a subsite!
    var siteColl = context.get_site();
    web = siteColl.get_rootWeb();
    var groupCollection = web.get_siteGroups();
    // Get the Our Group's ID
    var _group = groupCollection.getById(groupID); // ID of the Group that we are checking
    var users = _group.get_users(); // Get all Users of the group
    this._users = users;
    this._currentUser = web.get_currentUser(); // Get current user
    this._isInThisGroup = isInThisGroup;
    context.executeQueryAsync(Function.createDelegate(this, this.CheckUserSucceeded), Function.createDelegate(this, this.failed));

//The below Checks  if User is the member of the specified group
function CheckUserSucceeded() {

    if (this._users.get_count() > 0) {
        var _usersEnum = this._users.getEnumerator();
        while (_usersEnum.moveNext()) {
            var user = _usersEnum.get_current();
            if (user.get_loginName() == this._currentUser.get_loginName()) {
                arrIsInThisGroup[this._isInThisGroup] = true;

function failed(sender, args){alert("error");}

8. Next Build and deploy.