
I have a situation where I am using apex to create an account, then an opportunity, and then a single opportunity line item via 1 class. The problem I am running into is if a DML exception is triggered at the Opportunity or Opportunity Line Item level. In those cases the Account has already been created which is not the behaviour I want. What I would like is to ensure all 3 components are created or none of them at all. What would be the best practise here?
public PageReference ProcessRegistrant(){
opportunity o = new opportunity([...]);
try{
insert o;
}Catch(DMLexception e){
ApexPages.addMessages(e);
}
OpportunityLineItem oli = new OpportunityLineItem([...]);
try{
insert oli;
}Catch(DMLexception e){
ApexPages.addMessages(e);
}
return null;
}
2 answers
You can use Database.setSavePoint() and Database.rollback() to accomplish this.
Here's some documentation on it: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database.htm