1

I am writing a code which supposed to process a list of ActivityHistories for any SObject which supports them (like Opportunity, Account, etc). And at that point it's impossible to know what is the exact SObject type.

Here is my problem. I can get ActivityHistories for a known SObject type, like this:

Opportunity opp = Database.query(
    'SELECT (SELECT Id, Subject, Status, Priority, OwnerId, WhoId '
    + 'FROM ActivityHistories '
    + 'ORDER BY CreatedDate DESC '
    + 'LIMIT 10 OFFSET 0 ) '
    + 'FROM Opportunity '
    + 'WHERE Id = \'0061100000E8pC1\' '
    + 'LIMIT 1');
System.debug(opp.ActivityHistories);

But how to get the list of ActivityHistories in the case below?

Id fid = '0061100000E8pC1';
SObject obj = Database.query(
    'SELECT (SELECT Id, Subject, Status, Priority, OwnerId, WhoId '
    + 'FROM ActivityHistories '
    + 'ORDER BY CreatedDate DESC '
    + 'LIMIT 10 OFFSET 0 ) '
    + 'FROM ' + fid.getSobjectType().getDescribe().label
    + ' WHERE Id = \'' + fid
    + '\' LIMIT 1');
  • 2
    You shouldn't be using the label.... You want the api name instead there, by the way – Sebastian Kessel Feb 17 '17 at 22:13
  • 1
    Technically, it's simply more efficient to say String.valueOf(fid.getSObjectType()) instead. – sfdcfox Feb 17 '17 at 22:22
  • @sfdcfox you can just use type coercion and drop String.valueOf entirely since you're doing concatenation. – Adrian Larson Feb 17 '17 at 22:30
2

Use the getSObjects method.

system.debug(record.getSObjects('ActivityHistories'));

You can call it on any SObject instance including opp or obj. Note that a single instance isn't an object in proper terminology, but rather a record.

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.