8

We have a scenario where in the before insert trigger of object Asset, which looks for a duplicate and if a duplicate is found a record is inserted in the junction table and after the dml is complete, we have an adderror method throw an error message letting the user know of the situation.

The problem is that the DML on the junction object is completed but rolled back when adderror method executes.

Things i have tried.. Having a savepoint, Saveresult, Writing the dml of junction object in another class, setting the allornone parameter to false and none of these have helped.

1

2 Answers 2

6

This is, quite sadly, not possible as I discovered on this answer is that if all rows in the trigger have addError called on them than any DML (which, technically speaking, includes things like sending email and calling @future methods) is rolled back.

In short, if all rows in the trigger fail to save than any byproducts of the trigger execution are rolled back.

1
  • More of a general question but, what if only one record has an error? Aren't all DML operations for all trigger context records rolled back as well regardless of if the others have errors? (Assuming the all or none flag isnt set to false)
    – Phil B
    Commented Jul 9, 2013 at 14:59
1

Do you want the transaction to fail or not ;) I assume "not really".

If you have to stick to standard pages - you might move population of junction object to an @future method. I haven't tried it in failure scenario - it might turn out that @futures aren't queued up if transaction fails, similar to how email sending happens only after succesfull transaction.

Much saner way would be to have some kind of top level control though (for example visualforce page + controller extension) for the Asset creation. You could perform the uniqueness check upfront or simply wrap it in a try-catch block (if the logic really has to be in the trigger) that would capture the error message (maybe phrase it nicer so user sees something more meaningful than big nasty red error + stacktrace)...

try {
    insert assets;
} catch(DMLException e) {
    insert junctionObjects;
    endUserMessage = '10 Assets created, 5 found to be dupes, linked instead';
} 
2
  • 2
    I tried the same with the @future method. Somehow didnt work for me.
    – swatkat
    Commented Mar 12, 2013 at 18:33
  • 1
    Yup @future doesn't help as rollback would prevent it from happening.
    – Ganesh
    Commented Mar 13, 2013 at 4:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .