Saturday, July 5, 2014

Salesforce: Object Prefix

For Salesforce administrators and developers with years of experience work in Salesforce area, all of us should know 0015000000tCKZx is an Account record while 00350000023hJC0 is a Contact. You can easily note this in the web page URL. This also serve as record Id whether as 15 or 18 characters. Looking the first 3 characters prefix, we can  determine what is the object behind that record in both Standard and Custom object.

Standard Object
For standard object, all the prefix is the same. I am not going to re-list each Standard object with the correspondence prefix, as many of fellow blogger and Salesforce article has list it:

Custom Object
Each custom object have unique prefix for each instance, it is the same with standard object where prefix length = 3 characters. You can notice it in the URL when open the record or click custom object tab for that object. Here a blog written sometimes back to get a tab view without have to create custom object tab - Hidden Tab for Custom Object

But, if the object just created and no tab is create for it, you would be a little difficult to get the prefix as it is not state anywhere in Salesforce. Here is the workaround - use a free tool Developer Workbench

Once you login, go to Standard and Custom Objects menu, select the object from dropdown and look for keyPrefix, see screenshot below: 

Another use case, you have a Salesforce record Id, but do not know what is the object for that record Id. Go through each object using Developer Workbench is way too hard. Use Developer Console with simple apex script will easily find the object. Click your name in Salesforce then click Developer Console

Once Developer Console open, click Debug then Open Execute Anonymous Window

It will show last apex code executed (if any), change the code to following and click Execute button.

System.debug(System.LoggingLevel.ERROR, Id.valueOf('01Q50000000IhVI').getSObjectType());

See the highlight, 01Q50000000IhVI is a record for Competitor__c custom object.

Using Developer Console also can find prefix as we did using Developer Workbench, use following apex code: 
Schema.DescribeSObjectResult r = CustomObject__c.sObjectType.getDescribe();
String keyPrefix = r.getKeyPrefix();
System.debug('Printing --'+keyPrefix );

Or in one line command
System.debug('keyPrefix: ' + CustomObject__c.SObjectType.getDescribe().getKeyPrefix());

Change CustomObject__c to your real object API name. Here is the result:

RegEx to validate Salesforce Id
If you familiar with RegEx, here is the regex to validate Salesforce Id