How to get RecordType Id efficiently in Apex with caching

It is very common needing to get recordtypeId when we are working in Salesforce. There are multiple ways to do it. Here we will go through different ways and find the best way.

Different approaches

  1. SOQL against RecordType standard object

    [SELECT Id, Name FROM RecordType WHERE Name = 'Master' AND SObjectType = 'Account']

    This approach count against the number of SOQL queries.

  2. Get recordtype ID in apex without caching

    public with sharing class RecordTypeUtil {
    //Do not use this
    public static Id getRecordTypeIdWithoutCache(String objectName, String recordtypeName) {
    Map<String, Schema.SObjectType> sObjectTypeMap = Schema.getGlobalDescribe();
    Schema.SObjectType sotype = sObjectTypeMap.get(objectName);
    Map<String, Schema.RecordTypeInfo> recordTypeMap = sotype.getDescribe().getRecordTypeInfosByName();
    return recordTypeMap.get(recordTypeName).getRecordTypeId();
    }
    }

    Since this approach do not cache operations like Schema.getGlobalDescribe() and sotype.getDescribe().getRecordTypeInfosByName() performance will not be great

  3. Get recordtype ID in apex with caching USE THIS APPROACH

    public with sharing class RecordTypeUtilWithCache {
    private static Map<String, Schema.SObjectType> sObjectTypeMap = Schema.getGlobalDescribe();
    private static Map<String, Map<String, Schema.RecordTypeInfo>> soTypeToRecordTypesMap = new Map<String, Map<String, Schema.RecordTypeInfo>>();
    public static Id getRecordTypeId(String objectName, String recordtypeName) {
    Schema.SObjectType sotype = sObjectTypeMap.get(objectName);
    Map<String, Schema.RecordTypeInfo> recordTypeMap = soTypeToRecordTypesMap.get(objectName);
    if(recordTypeMap == null) {
    recordTypeMap = sotype.getDescribe().getRecordTypeInfosByName();
    }
    Schema.RecordTypeInfo recordTypeInfo = recordTypeMap.get(recordtypeName);
    if (recordTypeInfo != null) {
    return recordTypeInfo.getRecordTypeId();
    }
    return null;
    }
    }

    Here we cache expensive schema describe operations. Allowing multiple calls to the same method to perform efficient and fast in same transaction.

    You can get recordtype Id using the syntax RecordTypeUtilWithCache.getRecordTypeId('Account', 'RecordTypeNameHere');

No comments:

Post a Comment