Retrieving sObject RecordTypeId in Apex

Usually we required to get the sObject record type id when working in Apex. There are different ways to get the record type Id in Salesforce.

We can query from RecordType object to get the record type type id of the object, like below syntax-

RecordType rt = [SELECT Id FROM RecordType WHERE SObjectType = ‘OBJECT NAME‘ AND DeveloperName = ‘RECORDTYPE NAME‘ LIMIT 1];

RecordType accRecTypeId = [Select id from RecordType where sObjectType = ‘Account’ and DeveloperName =’Person Account’ ];

This works fine, but it will use one query against our query governor limit which may create issue in different scenario.

Instead of SOQL query, its preferable to use dynamic apex to get RecordTypeId. Here is the way to do this without any query:

Id accRecordTypeId = Schema. SObjectType. Account. getRecordTypeInfosByName().                                                                                         get(‘Person Account’).getRecordTypeId();

Best way to access record type id using Schema which does not count in Salesforce SOQL governors limit. In below code, instead of hard coding the object name and record type label, dynamic approach which give flexibility to admin or developer.

 public class ObjectUtility {  
   public static Map<String,Schema.RecordTypeInfo> recordTypeInfoMap = new Map<String,Schema.RecordTypeInfo>();  
   public static Id getObjectRecordTypeId(String sObjectName, String recordTypeName) {  
     sObject obj;  
     Schema.SObjectType sObjectType = Schema.getGlobalDescribe().get(sObjectName);  
     if(sObjectType != null) {  
       obj = sObjectType.newsObject();  
       Schema.DescribeSObjectResult sObjDesc = obj.getSObjectType().getDescribe();  
       if(sObjDesc != null) {  
         recordTypeInfoMap = sObjDesc.getRecordTypeInfosByName();  
       if(!recordTypeInfoMap.containsKey(recordTypeName)) {  
         throw new RecordTypeException('Record type "'+ recordTypeName +'" does not exist.');  
       } else {  
         return recordTypeInfoMap.get(recordTypeName).getRecordTypeId();  
     return null;  
   public class RecordTypeException extends Exception{}  

Now you can retrieve SObject RecordType Id without any queries using the following code:

Now pass parameters to above method. Parameters are: Object name and Record Type label. Do not pass developer name.

ID RecordTypeId = ObjectUtility.getObjectRecordTypeId(‘Account’ , ‘PersonAccount’);

2 thoughts on “Retrieving sObject RecordTypeId in Apex

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s