+ Start a Discussion
shreya duggalshreya duggal 

prevent rollback with addError in Apex Trigger

I have a trigger which is added to object A in which I need to show error on save button but at the same time I need to insert record in a custom object B. I am using trigger.new[0].addError('Message') and then using database.insert to insert the data in the custom object B but the record is not getting created as I read in documentation that addError rollbacks the DML operation but I need both the error and DML operation to function.  Can anyone help me with this?
Hi Shreya,

Probably its because of the order of the code that you have written. Could you share the code snippet here.

shreya duggalshreya duggal
Here is the code:
 trigger EmployeeUpdate on Employee__c (before update) {
    List<Employee__c> Employees = [select ID from Employee__c where ID =: trigger.new[0].id];
    Job_Posting_Sites__c obj=new Job_Posting_Sites__c(
    database.saveResult sr = database.insert(obj, false);   
    if(Employees.size() > 0){       
        trigger.new[0].addError('You can not update this Employee and its related record. System administrator is notified about this.');        

Please let me know if the order is wrong?