Retrieving SObject RecordTypeId Dynamically with Salesforce

All too often while developing on the Force.com platform I've needed to obtain the Id of an SObjects Record Type based off the RecordType Name. Many times people will go about accomplishing this by querying the RecordType object directly like the following:

RecordType rt = [SELECT Id FROM RecordType WHERE SObjectType='OBJECT_NAME_HERE' AND Name='RECORDTYPE_NAME_HERE' LIMIT 1];

Now this works just fine, but it goes against our query governor limits which could potentially cause issues in all sorts of different scenarios. (e.g. Unit testing, Large applications with many queries, etc.)

I prefer to use Apex describe methods to accomplish the task:

//Generate a map of tokens for the sObjects in your organization
Map gd = Schema.getGlobalDescribe();

//Retrieve the describe result for the desired object
DescribeSObjectResult result = gd.get('Account').getDescribe();

//Generate a map of tokens for all the Record Types for the desired object
Map recordTypeInfo = result.getRecordTypeInfosByName();
system.debug('RECORD TYPES:' + recordTypeInfo);

//Retrieve the record type id by name
String recordTypeId = recordTypeInfo.get('RECORDTYPE_NAME').getRecordTypeId();

Obviously that is far more code to accomplish the same task. So what I've done is wrapped this code in a generic method that I've placed in my ObjectUtil class, which is a class I use to group utility functions for working with objects in Salesforce.

EDIT: I've refined the method below to further bulletproof the code by type checking it with the compiler, reducing the possibility for error if an SObject doesn't exist.

public class ObjectUtil 
{
    public static String getObjectRecordTypeId(SObjectType sObjectType, String recordTypeName)
    {
        //Generate a map of tokens for all the Record Types for the desired object
        Map recordTypeInfo = sObjectType.getDescribe().getRecordTypeInfosByName();

        if(!recordTypeInfo.containsKey(recordTypeName))
            throw new RecordTypeException('Record type "'+ recordTypeName +'" does not exist.');

        //Retrieve the record type id by name
        return recordTypeInfo.get(recordTypeName).getRecordTypeId();
    }

    public class RecordTypeException extends Exception{}
}

Now I'm able to retrieve SObject RecordType Id's without any queries using the following code:

String recordTypeId = ObjectUtil.getObjectRecordTypeId(Lead.SObjectType, 'RECORDTYPE_NAME');

Hope this was helpful!

Vote on HN


comments powered by Disqus