1

I'm using v31.0 of the Salesforce REST API. When looking at the metadata for some of my objects, Salesforce says that the OwnerId field references two tables: Group and User. The JSON that Salesforce returns looks like this:

...
referenceTo: [
  "Group",
  "User"
}
....

How can I tell which type of object to grab the Name value from? For example, for fields not referencing multiple types, I simply take the referenced object, and put it in a query to find the name value.

'select name from ' + referenceTo[0]

How can I find out this information when the field is referencing multiple types?

1

You can describe each object in referenceTo, and check the keyPrefix attribute against the Id. The key prefix is the first three characters of an Id. I recommend describing all objects that you'll be using and cache those describe results for later use.

| improve this answer | |
1

If you would rather skip the separate query on the referenced objects, e.g. on User or Group in the case of OwnerId, you can usually safely query on the Name field using relationship syntax, e.g. Owner.Name, and Salesforce will fill in a Name field value for whatever type of object is referenced, e.g. the User's name, Group's Name, or, for objects that don't have a field called Name, such as Solution and Case, Salesforce will take the corresponding Name fields, e.g. SolutionNumber and CaseNumber, and return those.

For instance, the Task and Event objects have a What field which can point to tons of different standard or custom objects. But you can always query on What.Name and expect to get a result. This saves you from having to do a separate SOQL query on the corresponding related object just to get the Name field value:

select Subject, ActivityDate, WhatId, What.Name
from Task
where Priority = 'High' 
and IsClosed = false

In this query, if the What in question is a Case, What.Name would return the Case's CaseNumber field, e.g. 00001234, whereas if the What was an Account, it would return the Account's Name field, e.g. 'Salesforce.com'

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.