Get SobjectType From Salesforce ID

Saturday, December 1, 2012


The Salesforce Winter 13 arrived with loads of new methods and upgrades.
From the long list of methods, Salesforce also  has provided a new method "getSObjectType()" for ID data type. This comes with lot relief as prior to API 26.0 there were no such method available by which we can get the sObject Type from Id of the sObject, instead we have to describe every object and match the prefix with the given sObject. A very resource hungry process.


 Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();  
 Schema.DescribeSObjectResult r = gd.get(sObj).getDescribe();  
 String tempName = r.getName();  
 String tempPrefix = r.getKeyPrefix();  
 String ObjId= [SELECT Id FROM Account LIMIT 1];  
 String tPrefix = ObjId.subString(0,3);  
 //Get the Sobject Type  
 String objectType = keyPrefixMap.get(tPrefix);  
                                                                                                                            *above code is no longer needed



But with arrival of Winter 13 / 26.0 API you can directly get the Sobject Type By calling the "getSObjectType()" method.


/*IMPORTANT : replace "sObjId" with your sobject Id, you need not to query the record again,   
 just use the Id field from your record set/ record*/  
 Id sObjId = [SELECT Id FROM Account LIMIT 1].Id;  
 Schema.SObjectType token = sObjId.getSObjectType();  


This new method will be really helpful in writing dynamic apex code for triggers and batches and even for visualforce controllers.


No comments:

Post a Comment