Ribbon Customization Part 11:Enable,Disable Ribbon button based on Security Role

After  a small gap I am blogging again, as I have there  there is a requirement for the ribbon controls to he shown depending on the security role.

So in this post I am  going to show a  custom button, in the Case homepage grid  under the Actions group. and I will make this button to be enabled only when the user with the “System Admin”role has logged in and I don’t enable this button for the rest of the users. << and also this button has the functionality for the Resolve Case>>

Steps to follow

  1. Create a solution
  2. Add  the entity ‘case’
  3. Add a Javascript webresource with the following code and named as ‘CommonLibrabry’
  4. function UserHasRole(roleName) {

     

        var serverUrl = Xrm.Page.context.getServerUrl();

        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";

        oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "'";

        var service = GetRequestObject();

        if (service != null) {

            service.open("GET", oDataEndpointUrl, false);

            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");

            service.setRequestHeader("Accept", "application/json, text/javascript, */*");

            service.send(null);

            var requestResults = eval('(' + service.responseText + ')').d;

            if (requestResults != null && requestResults.results.length == 1) {

                var role = requestResults.results[0]; 

                var id = role.RoleId;

                var currentUserRoles = Xrm.Page.context.getUserRoles();

                for (var i = 0; i < currentUserRoles.length; i++) {

                    var userRole = currentUserRoles[i];

                    if (GuidsAreEqual(userRole, id)) {

                        return true;

                    }

                }

            }

        }

     

        return false;

    }

     

    function GetRequestObject() {

        if (window.XMLHttpRequest) {

            return new window.XMLHttpRequest;

        }

        else {

            try {

                return new ActiveXObject("MSXML2.XMLHTTP.3.0");

            }

            catch (ex) {

                return null;

            }

        }

    }

    function GuidsAreEqual(guid1, guid2) {

        var isEqual = false;

        if (guid1 == null || guid2 == null) {

            isEqual = false;

        }

        else {

            isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();

        }

     

        return isEqual;

    }

     

    function callMain() {

     

    if(UserHasRole("System Administrator"))

    {

    return true;

    }

    else 

    {

    return false;

    }

     

    }

  5. Export the solution
  6. Unzip the solution
  7. Edit the customization
  8. Add the below custom action to display the button under the –Actions Group in the HomepageGrid
  9. <CustomAction Id ="sample.HomepageGrid.incident.MainTab.Actions.CustomAction" 

    Location ="Mscrm.HomepageGrid.incident.MainTab.Actions.Controls._children" 

                           Sequence ="10">

              <CommandUIDefinition>           

                  <Button Id="sample.HomepageGrid.incident.MainTab.Actions.Button"

                          Command="sample.HomepageGrid.incident.MainTab.Actions.Command"

                          LabelText="$LocLabels:sample.HomepageGrid.incident.MainTab.Actions.LabelText"

                          ToolTipTitle="$LocLabels:sample.HomepageGrid.incident.MainTab.Actions.LabelText"

                          ToolTipDescription="$LocLabels:sample.HomepageGrid.incident.MainTab.Actions.ToolTip"

                          TemplateAlias="o1"

                          Image16by16="/_imgs/ribbon/AddEmail_16.png"

                          Image32by32="/_imgs/ribbon/Email_32.png" />             

              </CommandUIDefinition>         

            </CustomAction>

  10. Define the command definition., basically this button has the functionality of << Resolving a case>>
    1. this will enable when only one record is selected in the Grid and also if the user has the ‘System Administrator” Role
    2. <CommandDefinition Id="sample.HomepageGrid.incident.MainTab.Actions.Command">

                 <EnableRules>

                   <EnableRule Id="Mscrm.CustomcheckRole" />

                   <EnableRule Id="Mscrm.SelectionCountExactlyOne" />             

                   <EnableRule Id="Mscrm.VisualizationPaneNotMaximized" />

                 </EnableRules>

                 <DisplayRules>

                   <DisplayRule Id="Mscrm.CanChangeIncidentForm" />

                 </DisplayRules>

                 <Actions>

                   <JavaScriptFunction FunctionName="Mscrm.IncidentActions.resolveCase" Library="/_static/_common/scripts/ribbonactions.js">

                     <CrmParameter Value="FirstSelectedItemId" />

                     <CrmParameter Value="SelectedControl" />

                   </JavaScriptFunction>

                 </Actions>

               </CommandDefinition>

  11. Provide the appropriate Display rule as well as the Enable rules as shown below
  12. <DisplayRules>

               <DisplayRule Id="Mscrm.CanChangeIncidentForm">

                 <EntityPrivilegeRule EntityName="incident" PrivilegeType="Write" PrivilegeDepth="Basic" />

                 <EntityPrivilegeRule EntityName="incident" PrivilegeType="AppendTo" PrivilegeDepth="Basic" />

                 <EntityPrivilegeRule EntityName="activitypointer" PrivilegeType="Create" PrivilegeDepth="Basic" />

                 <EntityPrivilegeRule EntityName="activitypointer" PrivilegeType="Append" PrivilegeDepth="Basic" />

               </DisplayRule>            

             </DisplayRules>

             <EnableRules>

               <EnableRule Id="Mscrm.SelectionCountExactlyOne">

                 <SelectionCountRule Minimum="1" Maximum="1" AppliesTo="SelectedEntity" />

               </EnableRule>

               <EnableRule Id="Mscrm.VisualizationPaneNotMaximized">

                 <CustomRule FunctionName="Mscrm.RibbonActions.disableButtonsWhenChartMaximized"

             Library="/_static/_common/scripts/RibbonActions.js">

                   <CrmParameter Value="SelectedControl" />

                 </CustomRule>

               </EnableRule>

               <EnableRule Id="Mscrm.CustomcheckRole">

                 <CustomRule FunctionName="callMain"

     Library="$webresource:new_CommonLibrary">

                 </CustomRule>

               </EnableRule>

             </EnableRules>

  13. Provide the locales as shown below
  14. <LocLabels>

             <LocLabel Id="sample.HomepageGrid.incident.MainTab.Actions.LabelText">

               <Titles>

                 <Title languagecode="1033"

                         description="Custom Button1" />

               </Titles>

             </LocLabel>

             <LocLabel Id="sample.HomepageGrid.incident.MainTab.Actions.ToolTip">

               <Titles>

                 <Title languagecode="1033"

                         description="Custom Button1" />

               </Titles>

             </LocLabel>

           </LocLabels>

  15. The screenshot appears as  shown below. when I logged with a user having system Admin role
  16. EnableRibbon button based on securityrole_CRM2011
  17. The screenshot appears as  shown below. when I logged with a user who doesn’t have system Admin role
  18. disable ribbon button based on security Role_CRM 2011
  19. The entire source code can be downloaded from here
  20. Happy learning Smile
About these ads

20 Responses to Ribbon Customization Part 11:Enable,Disable Ribbon button based on Security Role

  1. tammy says:

    you are doing a great job Siva. Thanks so much!!

  2. Mike Agee says:

    Is it possible to do this for say the ExportToExcel button on say the account grid?

  3. Mike Agee says:

    OK – I discovered a solution. With a combination of this excellent blog and the information I found at http://howto-mscrm.blogspot.com/2011/04/how-to-series-6-how-to-overrideenable.html
    I was able to accomplish disabling the ExportToExcel button even if the privilege is enabled for the current security role. Often doing something for a custom element does not directly apply for out-of-box elements and this was such a case, so it took coming at this from two directions to solve. Thanks…

  4. Hi.

    Very interesting example, thanks!

    I was looking to disable/hide a native ribbon element – more specificaly a Group (Mscrm.HomepageGrid.queueitem.MainTab.Actions) – based on security role like your example. The unique difference is the group i

    If I use your approach, I can hide the native control ( or Set of ) and add a custom group/buttons copying exactly the native nodes and applying a customrule with your javascript, right?

    Thanks!

    • yes.you are correct.

      • Cam says:

        Hi

        I have a similar requirement, but I need to hide the custom Tab created based on a security role.
        How can this be done?

        Thanks

      • Cam says:

        Hi Again,

        In addition to my earlier question:

        - My custom tab is not entity specific only. So whenever a users opens the browser and logs in to CRM I need to attach an onLoad event to check the user role and display/hide the Tab.
        - Is it possible to set Focus on the Custom Tab?
        - Is it possible to display that tab first?

        Thanks

      • Hi Cam,
        Please check the below post to add the custom tab for the CRM 2011 Ribbon.. this soultion has ur requried feature like of always opening the custom tab first no matter you go to any entity

        Need to check whether the Enable rule for Tab works the same way as it works for the controls.( To enable or disable based on the user role)

      • Cam says:

        Thanks for that Siva… I was able to display my Custom Tab as default only when I changed the Sequence to “1″.

      • Cam says:

        Hi

        Any news on hiding the whole Tab?

        Thanks

  5. Dave says:

    hi, I have a question, it does not work for me.
    i added the solution. next i enter with the role Systema Administrator.
    but i can see the button disabled.

    something do know why?

    Thanks.

  6. zhai says:

    hi, is this done in CRM online? is it applicable for on-premise also? thanks.

  7. Krishna Prasad shetty says:

    Hi Shiva, I tried your approach in ms crm 2011 onpremise , but when I select the case record the custom button is not enabling, here my role is System Administrator.
    and some other button also not enabled (Send-DirectEmail ,Connect, Add to Queue,RunWorkflow and RunScript)

  8. Krishna Prasad shetty says:

    Hi.. Shiva ,,, I tried
    your solution in MS CRM 2011 onpremise version , and when login with Sales ManagerRole , i am not getting the ‘Records Group’in case entity ribbon. That is i cant create new case..What is the reason for this….

  9. bzalloua says:

    We used this code but on some custom ribbon buttons. The code worked fine – button disable/enable based on security role. The button will also enable after you select records in the view. However the performance was very poor. When I click on a record in the view – i would have to wait for 12 seconds, before i can click on the next record, and then so on so it was unworkable. I only noticed this with custom buttons, not standard buttons. As soon as you remove the javascript to check security role, it starts working fine again. Any help woudl be good. We were using rollup 7 and accessing CRM via VPN.

    • Hi Bzalloua,
      yes, it takes time as from the client side we are checking the security role of the logged in user.as this is a custom function and checking the security role of a logged in user from the client side takes a bit of time. There is no other way i can see to modify this script to improve the performance to acheive this functionality.

      Thanks!
      Siva

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: