Skip to main content
Below is the following code that needs to be modified as it contains a DML statement inside of FOR loop which isn't a good practice. Anyone here to help me out?

trigger IncidentTrigger on Trust_Incident__c (before update) {

     Trust_Incident_History__c tih = new Trust_Incident_History__c();

     for(Trust_Incident__c newInc : Trigger.New) {

        

        Trust_Incident__c oldInc =  Trigger.oldMap.get(newInc.id);

        

        if(newInc.Status__c != oldInc.Status__c || newInc.Description__c != oldInc.Description__c) {

           // Trust_Incident_History__c tih = new Trust_Incident_History__c();

            tih.Description__c = oldInc.Description__c;

            tih.Status__c = oldInc.Status__c;

            tih.Incident__c = newInc.id;

            tih.Name = newInc.Name;

            tih.ModifiedUser__c = oldInc.LastModifiedById;

            tih.LastUpdate__c = oldInc.LastModifiedDate;

            insert tih; 

        }   

    }

 

}

Thank You!
1 answer
  1. Aug 15, 2018, 4:07 PM
    Hi Gauthami. You can add each of the trust incident record to a list and insert all the records after the loop.Hope this helps you.

    trigger IncidentTrigger on Trust_Incident__c (before update) {

         Trust_Incident_History__c tih = new Trust_Incident_History__c();

        List<Trust_Incident__c> tihToUpdateList = New List<Trust_Incident__c>();

         for(Trust_Incident__c newInc : Trigger.New) {

            

            Trust_Incident__c oldInc =  Trigger.oldMap.get(newInc.id);

            

            if(newInc.Status__c != oldInc.Status__c || newInc.Description__c != oldInc.Description__c) {

               // Trust_Incident_History__c tih = new Trust_Incident_History__c();

                tih.Description__c = oldInc.Description__c;

                tih.Status__c = oldInc.Status__c;

                tih.Incident__c = newInc.id;

                tih.Name = newInc.Name;

                tih.ModifiedUser__c = oldInc.LastModifiedById;

                tih.LastUpdate__c = oldInc.LastModifiedDate;

                tihToUpdateList.add(tih);

            }   

        }

        insert tihToUpdateList;

    }
0/9000