0

Accessing fields from related records via custom lookup fields works like this: object.lookup_field__r.Name This piece of code would return the Name of the related record via custom lookup field lookup_field__c.

I can see that What and Who on Task object are somehow different.

Is it possible to access a field via What or Who lookups in the same or similar manner like I mentioned above?

I used to access fields by querying related records by WhatId and WhoId but it gets quite complicated, I am searching for clean and short approach to solve this problem.

2 Answers 2

1

One way could be to identify related object by its id in code or in formula field

example : - add a formula field and have this formula in it to get 'What' related object name

CASE(LEFT( WhatId , 3), '001', 'Account', '003','Contact','006','Opportunity','00Q','Lead','Other')

once you identify object, write a dynamic SOQL and use it.

let me know if it helps!

1
  • Thank you Megha, I'm already doing it using this approach. I thought there is a simpler solution.
    – justasd
    Commented May 7, 2014 at 9:21
1

PS Apologies, this is still documented as "Developer Preview", so this answer is more of an FYI. Just appears to be turned on in my developer edition org.

SOQL will sometime have "polymorphic" syntax to help query where a reference can be to various SObject types - see e.g. TYPEOF .

So if you have a Tasks where the WhoId references both Contact and Lead, you can run a query of this form to get the name for both types:

Task[] tasks = [select typeof Who when Contact then Name when Lead then Name end from Task];
for (Task t : tasks) {
    System.debug('>>> ' + t.Who.Name);
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .