[SalesForce] How to retrieve Profile name using typeof clause in SOQL for getting Hierarchy(User) type of custom settings

I want to retrieve name of Profile for which a hierarchy type of custom setting is defined. This custom setting is not organisation wide default, but is specific for a profile. I got to know recently in this question that 'Location' field of custom setting is a polymorphic field and can't be accessed directly, but needs TYPEOF clause.

I have used following query to access the profile name but it is returning me a code(prefix ID probably) of that profile rather than name:

SELECT setupOwner.Name, customField1__c, customfield2__c 
    FROM myUserSetting__c WHERE 
    SetupOwnerId NOT IN (SELECT Id FROM Organization)

Then I tried using following query:

SELECT TYPEOF What
    WHEN myUserSetting__c THEN setupOwner.Name,
    ELSE customField1__c, customfield2__c 
    FROM myUserSetting__c 
    WHERE SetupOwnerId NOT IN (SELECT Id FROM Organization)

But it is giving me syntax error. Not able to understand the typeof syntax and how to use it.

Best Answer

In my custom setting, I have following:

enter image description here

And to retrieve only profile names from custom setting, you may use as following code having a polymorphic query:

for(OverrideStandardButtons__c setting: [SELECT 
        TYPEOF SetupOwner
            WHEN Profile THEN Id, Name, UserType
        END
    FROM OverrideStandardButtons__c WHERE 
    SetupOwnerId IN (SELECT Id FROM Profile)]) {
    // fetch the profile defination
    Profile objProfile = setting.SetupOwner;

    System.debug(objProfile + '----' + objProfile.Name);
}

Result of code:

Profile:{Id=00e6F000002QmfaQAC, Name=System Administrator, UserType=Standard}----System Administrator

Profile:{Id=00e6F000002QmfcQAC, Name=Analytics Cloud Integration User, UserType=Standard}----Analytics Cloud Integration User

Related Topic