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.

Id recTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Industrial Deal').getRecordTypeId();

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.

// with a custom label. This assumes a custom label by the name OpportunityRecTypeIndustrialDeal exists
Id recTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(Label.OpportunityRecTypeIndustrialDeal).getRecordTypeId();

// with a custom setting. This assumes there is a custom setting object ObjectRecordTypeLabel__c that contains a field RecordTypeLabel__c
ObjectRecordTypeLabel__c ortl = ObjectRecordTypeLabel__c.getInstance('Opportunity-Industrial-Deal');
Id recTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(ortl.RecordTypeLabel__c).getRecordTypeId();

// with custom metadata. This assumes there is a custom metadata object ObjectRecordTypeLabel__mdt 
// querying against a custom metadata object doesn't count against soql limits
ObjectRecordTypeLabel__mdt ortl = [SELECT DeveloperName, MasterLabel 
                                     FROM ObjectRecordTypeLabel__mdt 
                                    WHERE DeveloperName='Opportunity-Industrial-Deal' 
                                    LIMIT 1];
Id recTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(ortl.MasterLabel).getRecordTypeId();

** 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.

Id RecTypeId;
try {
  RecTypeId = [SELECT Id, SobjectType, Name, DeveloperName
                 FROM RecordType
                WHERE SobjectType='Opportunity'
                      and DeveloperName='Industrial_Deal'
                LIMIT 1];
} catch (exception e) {
  // do appropriate error handling

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.

// a chain of methods to get the record type Id by label
Id recTypeId = Schema.getGlobalDescribe().get('Opportunity').getDescribe().getRecordTypeInfosByName().get('Industrial Deal').getRecordTypeId();

// break the describe methods apart at each step
Schema.SObjectType objType = Schema.getGlobalDescribe().get('Opportunity');
Schema.DescribeSobjectResult objTypeDesc = objType.getDescribe();
map recTypeMap = objTypeDesc.getRecordTypeInfosById();
Schema.RecordTypeInfo rtByName =  recTypeMap.get('Industrial Deal');

Apex File Naming Standards

5 Apr

Consistent file naming helps keep Visualforce and Apex classes easy to recognize and find. I’ve seen many orgs with both the good and the bad. Below is a table with naming suggestions. Some of them are mine, but most came from a presentation that I found referenced in a Trailhead module. The presentation is by Vivek Chawla. I recommend looking it over because it covers a lot of good stuff. Thank you Vivek.

Apex and Visualforce Naming

  • UpperCamelCase
  • Avoid using underscores.
  • Use full names where possible. Be consistent.
  • Test class should be named for the class they cover, and the word “Test” should be appended to the end.
Functional Type Name Suffix Examples
Trigger Trigger AccountTrigger
Trigger Handler TriggerHandler AccountTriggerHandler
VF Controller Controller AccountCloneController
VF Controller Extension ControllerExt AccountCloneControllerExt
Service Class Services AccountServices
Utility Class Util AccountDupeCatcherUtil
Selector Class Selector AccountSelector
Model / Wrapper Class Varies… Accounts / AccountWrapper
Web Service (SOAP) Ws AccountToolsWs
Web Service (REST) Rest AccountToolsRest
Email Service EmlSvc AccountCreateEmlSvc
Asynchronous (Future) Async AccountIntegrationsAsync
Asynchronous (Batch) Batch AccountMigrationBatch
Scheduled Apex Job AccountCleanupJob
Queueable Apex Que AccountSyncingQue
Visualforce Page -none- AccountClone
Visualforce Component Cmp AccountCloneCmp
Lightning Components -TBD-
Lightning Pages -TBD-

Workflow Rule, Field Update, and Email Alert Naming

Workflow Rules and their actions can also get unruly without consistent naming. Force365 published some good suggestions. Below are the ones that I refer to most.

Workflow Rule
[Object]: [Criteria Description i.e. Condition]

Workflow Actions
Field Update –
Set [Field] to [Value]
Email Alert –
Send [Template short description]
Task –
[Task Subject]


SlideShare: Salesforce Development Best Practices by Vivek Chawla
Blog: Force365 – Salesforce Naming Conventions – Declarative


Remove Last Comma or Other Characters from the End of a String

28 Mar


Removing the last comma is often needed when dynamically building a SOQL Select string. Salesforce quietly released a bunch of new string methods in Winter ’13 that I have started to really appreciate. One of the new methods is removeEnd() and removeEndIngoreCase(). These are great for removing that last comma.

String soql = 'Select ';
for (MySubClass MSC : MySubClassList) {
    soql += MSC.FieldName + ',';
soql = soql.removeEnd(',');
soql += ' From YourObject';

If your data structure is a simple list of strings, you don’t even need the removeEnd(). The String.join() will form the string without an ending comma.

String soql = 'Select ';
list FieldList = new list {'Id', 'Name', 'Field1__c', 'Field2__c'};
soql += String.join(FieldList, ',');
soql += ' From YourObject';


Here is how to remove the last comma of a string variable in Javascript.

MyStrVar = MyStrVar.replace(/,\s*$/, "");

Salesforce Describe Methods – Record Types, Fields, and Global Describe

6 Sep

Record Type Describe

Getting an object’s record type Id is simple with the statement below, and it avoids using a SOQL statment on the RecordType object. However, the method name is misleading because getRecordTypeInfosByName actually retrieves the record type with the Label and not the Name. Also, be careful because the name is case sensitive. A Null Pointer Exception will be thrown if the label does not match exact spelling and case, so add appropriate error handling.

// Return record type Id by DeveloperName 
Id MyRecTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('My_Dev_Name').getRecordTypeId()

// Return record type Id by Label
Id MyRecTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('My Record Type Label').getRecordTypeId();

Continue reading