Tuesday, 21 February 2012

Get sObject Name from Record ID.....!!!!

Sometimes there are scenarios when we use

string urlID = ApexPages.currentPage().getParameters().get('id');

and develop the functionality based on urlID .

What should we do, if sometimes urlID gives ID of Object 'X' and sometimes it gives
ID of 'Y' based on business requirement?

Here is what I did....






 urlId=ApexPages.currentPage().getParameters().get('id');

 Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
            
 Map<String,String> keyPrefixMap = new Map<String,String>{};
            
 Set<String> keyPrefixSet = gd.keySet();
           
 for(String sObj : keyPrefixSet){
               
 Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
               
 String tempName = r.getName();             
               
 String tempPrefix = r.getKeyPrefix();
              
 keyPrefixMap.put(tempPrefix,tempName);
             
 }
            
             
 string objtempPrefix =urlId.subString(0,3);
             
 string objname =keyPrefixMap.get(objtempPrefix );
         
             
 system.debug('object name--------------->'+objname );




The first three chars of a record id refer to the sobject the record is based on.
 IF urlId is ID of X , objname will be 'X'
 IF urlId is ID of Y , objname will be 'y'