+ Start a Discussion
maxoutmaxout 

Finding the api objectname/SObjectType by object Id

 

Hi there,

Found a post that it  uses a loop to search the item as the link at the bottom.

Another one build a custom map with getKeyPrefix as the map key, where the map better maintained by the system as well.

And both using string.subString(0,3) to get the prefix, which is better provided with an API.

 

Is there any better practise?

 I mean, if there is a system API on 'Schema' which accepts an ID as parameter, returning the sobjecttype.

 

http://boards.developerforce.com/t5/General-Development/Reg-Finding-the-objectname-using-object-Id/m-p/261111#M53051

 

http://boards.developerforce.com/t5/Apex-Code-Development/Updating-Lead-or-Contact-based-on-a-Task/m-p/114550

 

Cheers

sfdcfoxsfdcfox

getKeyPrefix is the best way to accomplish this task today. Regrettably, it does mean using a ton of describe calls, especially in Apex Code. Depending on your specific use case, you may also be able to use List.getSobjectType, which returns the API object name for a list of Sobject records obtained through a query. That's probably the best design one could advocate considering the limitations of the platform. Note that not all SObjects have a defined KeyPrefix, though (I don't have a specific example, but the documentation states that this scenario could occur).

SuperfellSuperfell

describe + getKeyPrefix can do it, but in the vast majority of cases, at the point in time when you got the Id, you can get the type of the Id at that point, so you shouldn't really have to do this.

maxoutmaxout

Thanks guys.

2 answers on different aspects.

Since the id contains the type info, so it is a matter of available APIs.

In practice, an extra type parameter being passed to balance the describe thing.

 

The case is to pass context from side bar or detail page to a custom page through page parameters.

On a page using {!$ObjectType.Object} is one option. 

However, it is the 3-char prefix. A loop is still needed.

Wondering if there is {!Object.Type} to get the type name, though passing a hardcode type string like 'account' could be an option.

 

Surprisingly, there are both a sObject.getRecordTypeInfosByName() and a sObject.getRecordTypeInfosByID.

 

Cheers