Get all record types available on sObject in APEX

Get all record types available on sObject in APEX
Get all record types available on sObject in APEX

Suppose that you want to get all record types of any standard or custom object in APEX class , here is the simplest way to solve your problem.

I have created two record types on Contact Object , Master is the default record type  available on every Object.

record types on contact object

Get All record Type

Here we are using Schema class to find record type , the below code will return all Standard and Custom record types available on Contact Object.

				
					Schema.DescribeSObjectResult describe =Schema.getGlobalDescribe().get('Contact').getDescribe(); 
Schema.RecordTypeInfo defaultRecordType;
for(Schema.RecordTypeInfo recordType : describe.getRecordTypeInfos()) {
    System.debug( recordType.getDeveloperName());
}
				
			

Get only Custom Record types

Given code help you to find all Custom record types of Contact Object .

				
					Schema.DescribeSObjectResult describe =Schema.getGlobalDescribe().get('Contact').getDescribe(); 
Schema.RecordTypeInfo defaultRecordType;
for(Schema.RecordTypeInfo recordType : describe.getRecordTypeInfos()) {
    if(recordType.isDefaultRecordTypeMapping()) {
        System.debug( recordType.getDeveloperName());
    }
   
}
				
			

Get Id of record type

To get the Id of record type use getRecordTypeId()  method .

				
					System.debug( recordType.getDeveloperName());
				
			

I hope this blog help you to learn something new . Please share with your Coders friends , don’t forget to subscribe our Youtube channal.

How the code works

getRecordTypeInfos() on the object describe returns one RecordTypeInfo for each record type, and the loop prints its developer name. The Master record type always appears in the list, even if you created no record types.

A mistake in the Custom record types snippet

The second snippet uses isDefaultRecordTypeMapping() to find custom record types. That method only tells you whether the type is the default for the current user, so it does not separate Master from custom types. Use isMaster() instead.

Correct code for custom record types

Schema.DescribeSObjectResult describe = Contact.SObjectType.getDescribe();
for (Schema.RecordTypeInfo rt : describe.getRecordTypeInfos()) {
    if (!rt.isMaster()) {
        System.debug(rt.getDeveloperName() + ' | ' + rt.getName() + ' | ' + rt.getRecordTypeId());
    }
}

This prints the developer name, the label and the Id of each custom record type. If you only want types the running user can use, also check rt.isAvailable().

FAQ

How do I get the Id of one record type by name?
Use Contact.SObjectType.getDescribe().getRecordTypeInfosByDeveloperName().get('Your_Developer_Name').getRecordTypeId(). It does not need a SOQL query.

Why not query the RecordType object?
You can, but the describe approach does not use up a SOQL query.

Leave a Reply