Trigger that saves all the activities and events of a contact before a contact is deleted. When a contact is deleted all the history related to that contact is deleted.
Your trigger has a number of logical errors.
- You are querying against the wrong Contact. You query against the
WhoIdof your dummy contact, while what you probably want to be doing is querying against a collection of deleted Contact Ids like
forloop. These are the records whose Events or Tasks you wish to preserve.
- You are not making any changes to the events, like reassigning their
WhoId. (If that is in fact what you plan to do).
- You are attempting to insert existing
Eventrecords, with a populated
Database.insert(). This will fail; you cannot insert records with an
Id, and it looks like you probably meant to perform an
- You've named a variable
event. Since Apex is a case-insensitive language, this looks the same as the class name
Eventto the compiler, which can cause very confusing errors. You do the same thing with
- You initialize
eventswith an empty list, which you don't need to do since you populate it from a query.
- You do not need to check
Trigger.isDelete && Trigger.isBefore, since your trigger runs only on the
I would suggest that you take some time to write out, in pseudo-code, what the logical flow of your trigger should look like, before you begin translating it into Apex. If you haven't already worked through Trailhead's trigger modules, especially Bulk Triggers, they might be a great help to you.