Wednesday, 17 August 2011

How To SOQL On ActivityHistory

ActivityHistory is one of those rare objects that you cannot directly run a soql statement on.
 eg: Select WhatId,CreatedDate From ActivityHistory];  is not allowed

So the trick is to place the soql within a nested soql. The Account object has a direct lookup field in the Task object, so the outer part of the soql can query the Account object first.

But say for instance you are interested on information in the history for Tasks related to another object, such as the Opportunity object. To get this information the following code could be used to grab this information.

Set<Id> opportunityIDsSet = new Set<Id>();
opportunityIDsSet.add(<<populate set with Opportunity IDs);

Map<ID,Datetime> oppMap = new Map<ID,Datetime>();
for (Account eachtaskhist: [Select id, (Select WhatId,CreatedDate From ActivityHistories where WhatId In :opportunityIDsSet << YOU COULD SET MORE SPECIFIC WHERE CRITERION AS YOU REQUIRE >>) From Account])

oppMap will contain a Map of (<<Opportunity IDs>>, <<Date of ActivityHistory Was Created>> )

Just a note on this however, there are certain objects in Salesforce that cannot be soqled on by users  other than by System Administrator users, ActivityHistory is one of those objects. So make sure you remove with Sharing in your classes.


1 comment:

  1. Hello. Question related to this post. I want to allow the User to page through ActivityHistory records for a given Account/Contact. So for example i want to query 100 ActivityHistory records at a time - and allow the user to click to see the next/previous 100. How would I manage this? OFFSET isn't available in subqueries...



Note: only a member of this blog may post a comment.