When an Account is created, this trigger checks for custom checkboxes to determine if a related Contact or Opportunity should be created. Opportunities are only created if the Account is marked “Active.”
For more hands-on practice, check out this YouTube playlist.
Solution:
trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){ if(Trigger.isAfter){
AccountTriggerHandler.createContactOrOpp(Trigger.New);
}
}
}
public class AccountTriggerHandler {
public static void createContactOrOpp(List accList){
List<Contact> conList= new List<Contact>(); List oppList=new
List<Opportunity>(); for(Account acc:accList){ if(acc.Contact__c){
Contact con = new Contact(); con.FirstName =
‘con1’; con.LastName = ‘last’; con.AccountId =
acc.Id; conList.add(con);
}
if(acc.Opportunity__c && acc.Active__c == ‘Yes’){
Opportunity opp = newOpportunity(); opp.AccountId = acc.Id;
opp.StageName = ‘Prospecting’; opp.CloseDate =
System.today();
opp.Name = ‘Opp1’;
oppList.add(opp);
}
}
if(oppList.size()>0){
insert oppList;
}
if(conList.size()>0){
insert conList;
}
}
}