// Build aRecord localtypes cache so that we don't request this multiple times
private static Map<Schema.SObjectType,Map<String,Id>> rtypesCache;
private static List<sObject> results;
static {
rtypesCache = new Map<Schema.SObjectType,Map<String,Id>>();//convenient map, formatted from results.
results = new List<sObject>();//contains all recordtypes retrieved via SOQL
}
// Returns a map of active, user-available RecordType IDs for a given SObjectType,
// keyed by each RecordType's unique, unchanging DeveloperName
publicprivate static Map<String, Id> GetRecordTypeIdsByDeveloperNamegetRecordTypeMapForObjectGeneric(
Schema.SObjectType token
) {
// Do we already have a result?
Map<String, Id> mapRecordTypes = rtypesCache.get(token);
// If not, build a map of RecordTypeIds keyed by DeveloperName
if (mapRecordTypes == null) {
mapRecordTypes = new Map<String, Id>();
rtypesCache.put(token,mapRecordTypes);
} else {
// If we do, return our cached result immediately!
return mapRecordTypes;
}
// Get the Describe Result
Schema.DescribeSObjectResult obj = token.getDescribe();
//Check if we already queried all recordtypes.
if (results == null || results.isEmpty()) {
// Obtain ALL Active Record Types for the given SObjectType token
// (We will filter out the Record Types that are unavailable
// to the Running User using Schema information)
String soql =
String soql = 'SELECT Id, Name, DeveloperName '
, +sObjectType 'FROMFROM RecordType '
+ 'WHERE SObjectType = \'' + String.escapeSingleQuotes(obj.getName()) + '\' '
+ 'ANDWHERE IsActive = TRUE';
List<SObject> results;
try {
results = Database.query(soql);
} catch (Exception ex) {
results = new List<SObject>();
}
}
// Obtain the RecordTypeInfos for this SObjectType token
Map<Id,Schema.RecordTypeInfo> recordTypeInfos = obj.getRecordTypeInfosByID();
// Loop through all of the Record Types we found,
// and weed out those that are unavailable to the Running User
for (SObject rt : results) {
if (recordTypeInfos.get(rt.Id) != null) {
if (recordTypeInfos.get(rt.Id).isAvailable()) {
// This RecordType IS available to the running user,
// so add it to our map of RecordTypeIds by DeveloperName
mapRecordTypes.put(String.valueOf(rt.get('DeveloperName')),rt.Id);
}
else {
System.debug('The record type ' + rt.get('DeveloperName') + ' for object ' + rt.get('sObjectType') + ' is not availiable for the user.');
}
}
}
return mapRecordTypes;
}
zachelrath's code makes soql query for every type of object. I.E. if we would retrieve recordTypes for 3 objects - Account, Opportunity and Contact, we'll make 3 SOQL queries. My code makes only 1 SOQL query which saves governor limits.
EvAzi
- 1.1k
- 9
- 25