How perform SOQL query where criteria input is based on user language

languagesoql

The context of this question is that I am developing a managed package. In the managed package there is functionality which should only be made available to system administrators. To check whether a user is a system administrator I have an apex method which gets their profile Id using UserInfo.getProfileId() and compares it to the system admin profile Id.

To get the system admin profile Id I have the following SOQL query –

SELECT Id, Name FROM Profile WHERE Name = 'System Administrator'

which works great…..except when the language of the user changes to anything other than English.

When the language changes no results will be returned because it is searching for the profile names assuming the input was in the users language. For example if my user language is Korean I need to perform the query as follows –

SELECT Id, Name FROM Profile WHERE Name = '시스템 관리자'

which will return the same result as the first query.

What is the best approach to handling this kind of situation? I am new to I18N in Salesforce so have no clue how to approach this. Should I use labels somehow? Is there a complete alternate approach to retrieving the profile?

Best Answer

Since profiles and permission sets have a 1-1 relationship, you can query the permission set without relying on the profile name. This is a more accurate way to check since multiple profiles can have PermissionsModifyAllData.

 Boolean hasModifyAll = [SELECT PermissionsModifyAllData FROM PermissionSet WHERE ProfileId = :UserInfo.getProfileId()].PermissionsModifyAllData;

It's also recommended to "cache" the value since the user never changes in a transaction to avoid additional queries.

public static Boolean MODIFY_ALL_USER {
    public get {
        if(MODIFY_ALL_USER == null) {
            MODIFY_ALL_USER = hasModifyAll();
        }
        return MODIFY_ALL_USER;
    }
    private set;
}

private static Boolean hasModifyAll() {
    return [SELECT PermissionsModifyAllData FROM Profile WHERE Id = :UserInfo.getProfileId()]?.PermissionsModifyAllData == true;
}
Related Topic