0

Writing an apex trigger that fires on on before Insert. However, if a record exists based on certain criterion I would like to change that insert action into an update action. I understand I can prevent the insert from happening by issuing an error

    account.name.addError('Duplicate in name'); 

but that is NOT what I want to do. I want to silently update where possible. Is there a way to accomplish this on a before insert trigger. Any examples of how we could change the insert operation to upsert within a trigger?

This is the trigger code and without throwing an error how do we change the insert that would happen after the trigger fires to an update?

trigger addAccountTrigger on Account (before insert) {
        //how do we do an update and prevent insert here?
}
  • Simply do a SOQL query on account and check if any account exists with the details provided for new account. If any account matches all the details, then change the dml operation to update instead of insert. – Ashish Sharma Aug 20 '18 at 10:18
  • 7
    Doing so can be done, but requires deleting records post-insert. It'd be a lot better to use the upsert command instead. – sfdcfox Aug 20 '18 at 10:19
  • Any example of code within a trigger where I can change dml operation to update/upsert? – user275157 Aug 20 '18 at 11:17
1

As there is no way to prevent insertion of record with successful transaction commit, if you add error in current record to prevent insertion it will roll back your update operation as well.

You can do this by implement after insert, inside this query the existing record and update that whatever you want

And than delete the current record.

So this will update the existing record

Using below code you can delete current record.

delete [ select Id from account where id in :Trigger.new];
| improve this answer | |
  • But the UI will show an error. I need a silent update. How would I achieve this? – user275157 Aug 22 '18 at 10:32
  • I have updated the comment. Future will not work in this scenario and this will also work silent update. – Chandra Kiran Aug 22 '18 at 10:34
  • Above approch worked for you? – Chandra Kiran Aug 22 '18 at 13:50
  • Yes...hopefully there is a way to avoid creation / deletion in the future. – user275157 Aug 26 '18 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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