When account is merged, what's the expected trigger order? Does the wining account get updated first or does the losing account get deleted? What happens when the child records are reparented?
1 Answer
From the Apex Developer Guide
Triggers and Merge Statements
Merge events do not fire their own trigger events. Instead, they fire delete and update events as follows:
Deletion of losing records
A single merge operation fires a single delete event for all records that are deleted in the merge. To determine which records were deleted as a result of a merge operation use the
MasterRecordId
field inTrigger.old
. When a record is deleted after losing a merge operation, its MasterRecordId field is set to theId
of the winning record. TheMasterRecordId
field is only set inafter delete
trigger events. If your application requires special handling for deleted records that occur as a result of a merge, you need to use theafter delete
trigger event.Update of the winning record
A single merge operation fires a single update event for the winning record only. Any child records that are reparented as a result of the merge operation do not fire triggers.
Example
For example, if two contacts are merged, only the delete and update contact triggers fire. No triggers for records related to the contacts, such as accounts or opportunities, fire.
Trigger Order of Execution The following is the order of events when a merge occurs:
- The
before delete
trigger fires.- The system deletes the necessary records due to the merge, assigns new parent records to the child records, and sets the
MasterRecordId
field on the deleted records.- The
after delete
trigger fires.- The system does the specific updates required for the master record. Normal update triggers apply.
-
1So how can you get triggers on the children to fire? I have an
on update
trigger on my child object. How can I get those to fire? Do I have to write a new trigger on the parent object, and if so how can I do that whenMasterRecordId
is not set until after thebefore delete
yet the child records won't have the deleted parentID in theafter delete
trigger?– ChanceCommented Feb 21, 2019 at 16:30 -
@Chance great question, and one i'd think would warrant it's own separate questions since i'm sure you're not the only one whose wondered this. high level, you'd need two parts, in the before delete you need to get a list of all the account ids, and then build a map of all related child records you care about firing the triggers on related to those ids. at this point you won't truly know if it's a merge or not, but need to have the information in case it is Commented Feb 22, 2019 at 19:12
-
@chance then, when the after delete fires, you can figure out which records were actually merged, by virtue of their id being present in your maps. you can then use the maps to find the related record and do an update call to fire triggers on them Commented Feb 22, 2019 at 19:13