0

In continuation with this question:

Background: I send a SingleApexMessage from apex code and want to associate it with a Lead so that a record of Activity History is created when this email is sent. For this, I am doing a setTargetObjectId with Lead Id on this email before sending it. This creates an activity history on Lead.

Requirement: 2 custom fields on this activity history should be populated as well.

Here is what I tried:

Approach 1: Query for EmailMessage and update it. Problem here is how to fetch EmailMessage related to Lead, which field identifies this?

Approach 2: Do not do a setTargetObjectId, instead create a new EmailMessage and populate it with all custom and standard fields. Problem here is how to relate this with Lead?

0

If we assume that the activity created by your code will be the most recently created activity on that Lead, you can do a SOQL query for

SELECT Id FROM Task WHERE Type = 'Email' AND WhoId = :myLead.Id ORDER BY CreatedDate DESC LIMIT 1

(obviously, filter as much as you can to avoid any possible errors) and that should give you the most recently created activity for that Lead.

I don't know if activities are created synchronously or asynchronously, so you'll need to test this out. But that would be the first way I'd try it.

1
  • Yes, I could do that but as you said, this does not look a reliable way to go with. What if another activity is created from a different thread in between my activity creation and SOQL query execution for the same lead? Maybe we can reduce the probability by adding more filters, but just checking for any more full proof method.
    – Sarang
    May 19 at 6:46

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.