function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Stefan Senegeac D.Stefan Senegeac D. 

Trigger to find duplicate entries based on email and update existing record

So far I've been able to identify duplicate entries on Account based on the email address and simply not insert them. The new records, even though they are duplicates, contain some new info (a custom id) and I want to assign that id to the existing record. Easier said than done. I've tried with before insert trigger to no luck then after insert with 'merge old new' but it won't let me (CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY) or (merge failed with invalid id field).
Is what I'm trying to do possible with apex/trigger? If so could you point me to some resources? If not, what's an alternative route?
Thanks.
pconpcon
Yes, what you are trying to do is perfectly suited for a trigger.  What you'll want to do is in an after insert trigger query for the object you want to merge it into and call the merge [1] method.

[1] https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_merge.htm
Stefan Senegeac D.Stefan Senegeac D.
Ok, found out the problem. I've done it in an after insert trigger. The problem was that I was trying to delete records directly referenced in Trigger.new (not 'delete Trigger.new' but a collection of Objects from Trigger.new). Apparently you have to get, for example, the Ids and store them, then delete the objects from trigger.new with a select statement (select Id from Object where Id in: collection). Before delete however I've updated the old records with the info from the new ones (simple update). It worked.