Get Record Type ID by Name for a Salesforce Object

14 Jan

Salesforce provides an Apex method for retrieving an object’s record type record id. The method accepts the record type label instead of the developer/api name, and this makes the Apex method sensitive record type label changes. Here is a typical example of the method in use. It strings together methods for the object’s schema, record type info, and record type id retrieval.

There are a few workarounds to prevent hard coding the record type’s label. The most popular is to use a custom label. A custom label can easily be updated when the record type label changes. Also, it won’t require changing Apex code, and it will come over when building/refreshing a sandbox. The downside is that you must remember to change both if the record type’s label changes. Other alternatives to a using a custom label include custom settings and custom metadata.

** You will want to handle exceptions with all of these techniques. First, if the record type is not found. Second, if the Custom Setting or Custom Metadata record was not found.

Querying the RecordType sobject is also possible, but not recommended because the query will count against the SOQL limits in the processing transaction.

The record type information can also be acquired through the global describe methods. This can be useful if you are retrieving other information about the object in addition to the record type. Describe methods return a lot of information about the object itself, the object’s fields, and relationships. Below is an example of using describe methods to get the record type Id.