Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Suggested answer

User Roles - NOT of current user!

Posted on by Microsoft Employee

Hi,

I need to be able to get the User roles of the owner of a record. Am able to get CurrentUserRoles but the current user may not be the owner of the record that has been selected. The reason for this is that we have an entity called staff records for one of the services that our organization provides.

Staff (of that service) may fit into one of 3 categories:-

  1. Management,
  2. Team Leaders, &
  3. Support staff.

Team leaders need to be able to see the records of Support staff but not there own or other Team leader records - so when they open a record the code (javascript) needs to be able to check whether that record belongs to a Support staff person or another Team leader (i.e. their being a Team leader is defined by a particular security role).

So I was hoping to find some function along the lines of 'getSecurityRoles(userGUID)' which, I assume, would return an array of the User's roles (guids) from which I could then match a role and immediately close the form/record if necessary - i.e. if it belonged to another Team Leader.

If anyone can help me with the code to resolve this it'd be greatly appreciated.

Regards, Doug.

  • Suggested answer
    Barkuma Profile Picture
    Barkuma 80 on at
    RE: User Roles - NOT of current user!

    Ended up going down a different track - here's the code that I used for anyone interested:-

    
    var userId = Xrm.Page.getAttribute("ownerid").getValue()[0].id;
    var role2Find = "Team Leader";
    var staffPersonIsTeamLeader = StaffHasThisRole(userId, role2Find);
    
    
    function StaffHasThisRole(userId, role2Find){
    
        var rolesOfUser = getUserRolesByID(userId);
    
        if (rolesOfUser.includes(role2Find)) {
            return true;
        }else{
            return false;
        }
    }
    
    
    function getUserRolesByID(userId) {   //- returns array of roles
    
        userId = userId.replace(/{/g, "");
        userId = userId.replace(/}/g, "");
    
            var xml =
                    [
                        "",
                            "",
                            "",
                            "",
                            "",
                            ""  
                            "",
                                "",
                                    "",
                                        "",  
                                    "",
                                "",
                            "",
                            "",
                        ""
                    ].join("");
    
            var fetchResult = XrmServiceToolkit.Soap.Fetch(xml);
            var roles = [];
    
            if (fetchResult !== null && typeof fetchResult != 'undefined') {
                for (var i = 0, ilength = fetchResult.length; i < ilength; i  ) {
                    roles[i] = fetchResult[i].attributes["name"].value;
    
                }
            }
    
            return roles;
    };

  • Suggested answer
    Barkuma Profile Picture
    Barkuma 80 on at
    RE: User Roles - NOT of current user!

    Thanks Mehran,

    It seems very close to working and is retrieving the roles as per retrieved = {results: Array (3)} but the subsequent line:-

    var results = retrieved.value;   ...leaves  results as 'undefined':-

    pastedimage1615418706578v1.png

    ...so I'm not sure why this is happening or where to go from here. Any suggestion appreciated.

    Regards, Doug.

    -------------------------------

    (edit) **>>  WORKING NOW !  >  modified  var results = retrieved.value;  to be  var results = retrieved.results;

    Also (in the loop) needed to modify var RoleId = results[i].RoleId.Value;  to  var RoleId = results[i].RoleId;

    Many thanks for the code Mehran - it's working perfectly now. However, when I try to flag your answer as a verified answer it says I don't have the right to edit it ??

    Doug.

  • Suggested answer
    MehranBre Profile Picture
    MehranBre 730 on at
    RE: User Roles - NOT of current user!

    Hi,

    use this function:

    function GetUserRoles(userId) {
    
        var serverUrl = Xrm.Page.context.getClientUrl();
        var oDataSelect = serverUrl   "/XRMServices/2011/OrganizationData.svc/"  
            "SystemUserRolesSet?$filter=SystemUserId eq guid'"   userId   "'&$select=RoleId";
    
        var retrieveReq = new XMLHttpRequest();
        retrieveReq.open("GET", oDataSelect, false);
        retrieveReq.setRequestHeader("Accept", "application/json");
        retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        retrieveReq.onreadystatechange = function () {
            if (retrieveReq.readyState == 4) {
                if (retrieveReq.status == 200) {
    
                    var retrieved = JSON.parse(retrieveReq.responseText).d;
                    var results = retrieved.results;
    
                    if (results.length > 0) {
    
                        for (var i = 0; i < results.length; i  ) {
    
                            var RoleId = results[i].RoleId;
    
                            // Store in Array or Check it or ...
                        }
                    }
                }
            }
        }
        retrieveReq.send();
    }

    Regards.

  • Suggested answer
    Charles Abi Khirs Profile Picture
    Charles Abi Khirs 3,569 on at
    RE: User Roles - NOT of current user!

    Hello,

    What I suggest is to use the CRMRestBuilder that allows you to build a webapi call to the needed entities and do the filter, with the ability to generate the code and test its result.

    Check this link for more details:github.com/.../CRMRESTBuilder

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans