Thursday, 1 November 2018

How to know object name from a record Id in dynamically ?

Hi All,

There are may ways to identify object name from the record id, Below is the simplest one.

String recId = '001hjhtthijhkfj';
String sObjName = recID.getSobjectType().getDescribe().getName();
System.debug('Printing-sObjName -'+sObjName ); --- Account

Here is my earlier post which talks about to get keyprefix of an object
https://salesforceworld4u.blogspot.com/search?q=getkeyprefix&_sm_au_=iHVtjW2rtVRrrS6r

Use Cases 

Lets assume we need to modify few fields of two different object records (Say Account and Contact), user has to modify from the detail page,

What will be our first step ?  We will create two custom detail page button (one for Account and another for Contact) .
Buttons will be linked to visual force page having standard controller Account/Contact.

The page will have a button "Save" , Save button function will be written in an extension class. At that time we should not create two extension class one for Account another for contact. We should be creating one extension class having one method which updates Account and Contact dynamically based on record id.

Public Account acc{get;set;}
Public Contact con {get;set;}
//constructor
public updateRecords(Apexpages.StandardController con){
    System.debug('Printing con...'+con.getId());
        String sRecordId = con.getId();
       
        if(sRecordId.subString(0,3) == Account.sObjectType.getDescribe().getKeyPrefix()){
        acc= new Account(Id = sRecordId);
        }
        else if(sRecordId.subString(0,3) == Contact.sObjectType.getDescribe().getKeyPrefix()){
        con = new Queue_View__c(Id = sRecordId);
        }
   
    }

If(acc !=null){
update acc;
}
if(con !=null){
update con;
}

1 comment:

CRMJetty said...

This is really interesting, you’re a very skilled blogger.
I have bookmarked this article page as I received good information from this.sugarcrm wordpress integration
Salesforce Customer Portal: Guide