Wednesday, January 02, 2019

Summer 18 : Better way to retrieve RecordTypeId

Salesforce Summer ‘18 has added new method to get Developer Name for Record Types which give me such a huge relieve.

my sketch
Previously, we were only able to get RecordType using Id or Name. Usually in our code we always need to retrieve the Id but retrieving Id with Name (Label) using getRecordTypeInfosByName is not good idea as Name can be changed easily.

To solve the issue, we created one Global class to run SOQL just to retrieve ID, DeveloperName. It exposed our code to SOQL limit and we need to be careful with the design when we decided to use Static because the global class can be called by different method in the same transaction.

Now we can forget about that *tedious part*. I started to clean up my code to use Salesforce method instead of using SOQL to retrieve record type.

Caution : Update your class API version to the latest version to prevent error as this new method not recognized in old version.

Retrieve RecordType ID using DeveloperName


Id newRecordType = Schema.SObjectType.Opportunity.getRecordTypeInfosById().get(opportunityId).getDeveloperName();

Retrieve RecordType DeveloperName using ID


String recordType= Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get(recordTypeDeveloperName).getRecordTypeId();

Please update the underlined word above with correct value.