In the previous article we have learned about How to check Object Permission Using Dynamic Apex in Salesforce which you can read from here. In this article I will tell you How to Fetch all Record Types of an Object using Dynamic Apex in Salesforce?
In this article, we will look at code example that demonstrates how to retrieve record type information of Account Object using Apex in Salesforce.
Below is the code snippet which fetches all record types of the Account Object.
// Create a Map to store Record Type names as keys and their corresponding IDs as values. Map<String, Id> recordType = new Map<String, Id>(); // Retrieve metadata about the Account object using Schema.DescribeSObjectResult. Schema.DescribeSObjectResult sobjectResult = Account.SObjectType.getDescribe(); // Get a list of all Record Type information for the Account object. List<Schema.RecordTypeInfo> recordTypeInfo = sobjectResult.getRecordTypeInfos(); // Iterate through each Record Type information and populate the Map with Record Type names and their IDs. for (Schema.RecordTypeInfo rt : recordTypeInfo) { recordType.put(rt.getName(), rt.getRecordTypeId()); } // Debug log the populated Map of Record Type names and IDs for verification. System.debug(recordType);
Let’s try to understand the code we have written above:
- Line 1: We initialized an empty map (
recordType
) to storeRecord Type
names as keys and their corresponding IDs as values. - Line 2: We fetched the metadata details about the
Account
object usingAccount.SObjectType.getDescribe()
. - Line 3: We retrieved a list of all
Record Types
for theAccount
object by callinggetRecordTypeInfos()
on the metadata. - Lines 4-6: We iterated through each
Record Type
in the list and populated the map:rt.getName()
was used to get the name of theRecord Type
.rt.getRecordTypeId()
was used to fetch its corresponding ID.
- Line 7: Finally, we logged the populated map in the debug log to verify the
Record Type
names and IDs.
After executing the code from anonymous window you will see the map in debug log. Here is what I saw when I executed in my Salesforce Org.

Also, check out the below video on How to fetch record type information using dynamic apex in Salesforce.
We hope now you know How to Fetch all Record Types of an Object using Dynamic Apex in Salesforce. If you have any doubts then let us know in the comment box below.