June 22, 2016

How to get Object Name from Id value in Salesforce?

Sample Code:

Visualforce page:

  1. <apex:page Controller="sample" sidebar="false" >  
  2. <apex:form >  
  3.     <apex:pageblock id="pg" >  
  4.         <apex:pageblockSection >  
  5.             <apex:pageBlockSectionItem >Record Id</apex:pageBlockSectionItem>  
  6.             <apex:pageblockSectionItem ><apex:inputtext value="{!recId}" /></apex:pageblockSectionItem>  
  7.         </apex:pageblockSection>  
  8.         <apex:pageBlockButtons >  
  9.             <apex:commandButton value="Find" action="{!find}" reRender="pg"/>  
  10.         </apex:pageBlockButtons>  
  11.         <apex:outputText >The object type is : {!objType}</apex:outputText>  
  12.     </apex:pageblock>  
  13. </apex:form>     
  14. </apex:page>  

Apex: Controller:

  1. public with sharing class sample {  
  2.   
  3.   
  4.     public Id recId {get;set;}  
  5.     public Schema.SObjectType objType {get;set;}  
  6.       
  7.     public void find() {  
  8.   
  9.   
  10.         objType = recId.getSobjectType();  
  11.         System.debug('Object Type is ' + objType);  
  12.   
  13.   
  14.     }  
  15.   
  16.   
  17. }  

Output:



3 comments:

  1. Id myId = 'aKZ340000004C97';
    // To retrieve the API Name.
    System.debug('Api Name' + myId.getSobjectType().getDescribe().getName());
    // To retrieve the Label.
    System.debug('Label' + myId.getSobjectType().getDescribe().getLabel());

    ReplyDelete