0

In before insert trigger I want to check if the record is already present and skip creation of a record if so. We use external backend system which sometimes fails and sends duplicate records (nobody wants fixing it).

In before insert trigger I tried to delete reference to a record, didn't work. AddError also doesn't work as we want to keep process bulkified and automated.

Is there a simple way to do this?

As an idea is after creation of records run scheduler which will find duplicates and remove the last one created. But it's not an easy way :_

2
  • Where are the data coming from? Do you have some unique External Identifier? If so, I recommend checking out upsert opertations using this External ID field. It will update the record if it exists, otherwise create. That way, you prevent duplication -- and in real time without batch jobs or code...
    – James
    Oct 21, 2015 at 15:56
  • Hi, of course you should consider fixing the external service but in the meantime have you considered using Duplicate Rules? trailhead.salesforce.com/en/content/learn/modules/… Aug 24, 2019 at 17:10

1 Answer 1

4

The appropriate want to do it would be to use the addError method:

for(Object var : trigger.new){
  //If meets criteria
  var.addError('Duplicate Found');
}

This is the bulkified way of doing it. What you may be missing is the integration, code, external systems need to set the allOrNone headers or database option, etc to false. This will allow records without an error to be inserted and return the results along with any errors to the external system.

Once the above is done, you will need to evaluate your code and the external integrations to identify and fix those that may not be setting the allOrNothing to false

If you can, use external ID's when sending data from an external system and use upsert. That will handle it without the trigger code. But it will depend on your external system and if you have any control of it or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.