Skip to content

Instantly share code, notes, and snippets.

@sholloway
Last active April 28, 2023 14:50
Show Gist options
  • Save sholloway/6244c6eb190ce5f266eb62fbb20af750 to your computer and use it in GitHub Desktop.
Save sholloway/6244c6eb190ce5f266eb62fbb20af750 to your computer and use it in GitHub Desktop.
Work with Salesforce Prefixes.
//Find an entity's prefix
String prefix = MyObjectType.SObjectType.getDescribe().getKeyPrefix();
System.debug(prefix);
class PrefixFinder{
public String findObjectName(String recordIdOrPrefix){
String objectName = '';
try{
String providedPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);
Map<String, Schema.SObjectType> allObjectsTypes = Schema.getGlobalDescribe();
for(Schema.SObjectType stype : allObjectsTypes.values()){
Schema.DescribeSObjectResult describeResult = stype.getDescribe();
String prefix = describeResult.getKeyPrefix();
if(prefix != null && prefix.equals(providedPrefix)){
objectName = describeResult.getName();
break;
}
}
}catch(Exception e){
System.debug(e);
}
return objectName;
}
}
//Given the prefix, find the object.
String objectName = new PrefixFinder().findObjectName('001');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment