+ Start a Discussion
David JobeDavid Jobe 

bulkify apex

I wrote this code, but every now and again I get the Too many DML statements error. I am thinking if I just have it batch at 150 a pop, I should be good, but none of my attempts seem to work. Any suggestions would be appreciated.

trigger NewOwnerWelcome on BXG_Contract__c (after update) {
    for (BXG_Contract__c acc :Trigger.new) {
    if(acc.timedelay__c == True){
        Case welcomecall                  = new Case();
        welcomecall.Description           = 'Give Owner Welcome Call';
        welcomecall.Routing__c            = 'Welcome Call';
        welcomecall.Area_Responsible__c   = 'Customer Care';
        welcomecall.Department__c         = 'UNO';
        welcomecall.Origin                = 'BXG Contracts';
        welcomecall.Contract_Number__c    = acc.BG_Contract_Number__c;
        welcomecall.BXGContracts__c = acc.id;
        insert welcomecall;
        }
}
}
Derek Hall 12Derek Hall 12
You have an insert statement embedded in a for loop. You should bulkify your insert to look like this:
 
trigger NewOwnerWelcome on BXG_Contract__c (after update) {
  List<Case> cases = new List<Case>();
  for (BXG_Contract__c acc : Trigger.new) {
    if (acc.timedelay__c == True) {
      Case welcomecall                  = new Case();
      welcomecall.Description           = 'Give Owner Welcome Call';
      welcomecall.Routing__c            = 'Welcome Call';
      welcomecall.Area_Responsible__c   = 'Customer Care';
      welcomecall.Department__c         = 'UNO';
      welcomecall.Origin                = 'BXG Contracts';
      welcomecall.Contract_Number__c    = acc.BG_Contract_Number__c;
      welcomecall.BXGContracts__c = acc.id;
      cases.add(welcomecall);
    }
  }
  if (!cases.isEmpty()) insert cases;
}