~

How to get RecordType Id efficiently in Apex with caching.

Explains and shared reusable and efficient way to get record type Id in apex.

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.

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

  1. 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');

[Top]

Comments

    No comments yet. Be the first to share your thoughts!

Phone

Office: +1 725 333 6699

Email

Office: admin@appcolab.com

Site: https://appcolab.com

Social
©2024 AppColab LLC · All rights reserved.