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
-
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.
-
Get recordtype ID in apex without caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspublic 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()
andsotype.getDescribe().getRecordTypeInfosByName()
performance will not be great -
Get recordtype ID in apex with caching USE THIS APPROACH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspublic 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