Validate Opportunity Creation with Database Methods

This example demonstrates using Database methods and addError() in triggers to validate Opportunities during insertion and handle errors gracefully.

For further learning, check this YouTube playlist.

Solution:

trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){ if(Trigger.isAfter){
                              AccountTriggerHandler.createOpp(Trigger.new);
                 }
           }
}
public class AccountTriggerHandler{

            public static void createOpp(List<Account> accList){
                                  List<Opportunity> oppList= new List<Opportunity>();
                                  for(Account acc:accList){
                                  Opportunity opp= new Opportunity();
                                  opp.Name=acc.Name; opp.AccountId=acc.Id;
                                  opp.StageName=’Prospecting’; //
                                  opp.CloseDate=System.today();
                                  oppList.add(opp);
            }
             Database.SaveResult[] srList=
             DataBase.insert(oppList,false); for(Integer
             i=0;i<srList.size();i++){ if(!srList[i].isSuccess()){ String
             errors=”; for(DataBase.Error err:srList[i].getErrors()){
             errors=errors+err.getMessage();
                       }
                       accList[i].addError(errors); }
                }
        }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)