The Easiest Way to Get Record Type Name in Apex

Zheng Yutian
2 min readJan 27, 2021

--

To get the RecordTypeId by Name, developers usually use .

Id clinicRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get(‘Clinic’).getRecordTypeId();

And there is a query we can run on RecordType object if we want it the other way around.

[Select Name from RecordType where ID = 'Id of the record type'];

What if I want to get the Record Type Name by Record Id? It seems easy, but most of the developers are doing it in a very complex way, and I have seen the following code, or something similar on countless projects.

Id recordId = ‘aed323000000sssUEYDs’;//get the object API nameString sObjectAPINAme = String.valueOf(recordId.getSObjectType());// build a dynamic query, here is the problem we can actually get the name from hereString queryString = ‘SELECT Name, RecordTypeId FROM ‘+sObjectAPINAme+’ WHERE Id =: recordId’;SObject recordTypeInfo = Database.query(queryString);// get all record types under the object
List<RecordType> recordTypes = [SELECT Id,DeveloperName FROM RecordType WHERE SobjectType=:sObjectTypeFromId];
//loop to find the matching record type
Id recordTypeId = (Id)recordTypeInfo.get(‘RecordTypeId’);
for(RecordType rt :recordTypes ) {
if(rt.Id == recordTypeId) {
System.debug(r.DeveloperName);
}
}

Instead of making it so complex and inefficient, just query the RecordType under sObject.

SELECT Name, RecordType.DeveloperName FROM Contact

Think twice before we start coding. There’s got to be an easier way. Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Zheng Yutian
Zheng Yutian

Written by Zheng Yutian

Salesforce Technical Architect at Publicis Sapient

No responses yet

Write a response