+ Start a Discussion

Apex Trigger code - 2 scenarios

Can someone help writing Apex Trigger for Cross object updates. The objects are Lead and Task (Related list) which is associated with the respective Lead. Here are a couple of cases for which am looking for -


1. When we email the lead, an acitivity gets created within Activity History Section. In each activity record, "Due Date" is the field gives the date of the completion of that activity. In this way list of activities listed in Activity History. I want to pull the last email date (from Due Date) for that lead and update a custom lead field (Last_Emailed_Date_c).


2. Similar to above while we send email and email ID gets bounce, an activity gets created with Subject having "bounced" word. When this activity recored created with bounced in Subjecline I want the respective Lead_Status_c (Picklist) getting updated to Disqualified.


I am not a programmer but can undertand the code at high level. It would be of great help if someone can share code for these two scenarios. Thanks a lot!!



Activities are related to the Lead via the WhoId reference field. When an activity is created that meets your criteria for inclusion, you can look up the WhoId and make sure it's a Lead, and then process accordingly. 



  1. Gather all the activites in your trigger set that need to be processed (perhaps all WhoIds starting with '00Q' and (Subject contains 'bounced' or Due Date is not null))
  2. Gather all the Lead Ids from the set of activities and soql them for future update (put them in a map of <Id,Lead>)
  3. Loop through your trigger set and get the right lead from your map by using Who Id
  4. Change the fields you want to change (you can compare the current Last Emailed Date value to what this activity has and only update if you want)
  5. If a lead changes, you might want to put it into a set for all your updated leads.
  6. Once you're loops are done, update your updated leads