An Apex trigger may be called with a batch of records. This for example happens when a bulk DML is executed. All records provided by the triggers
should be processed.
This rule raises an issue when specific records from the Trigger
are referenced, i.e. when it finds one of the following patterns:
-
Trigger.new[x]
-
Trigger.old[x]
-
Trigger.oldmap.get(x)
-
Trigger.newmap.get(x)
where x
is a hardcoded number.
Noncompliant code example
trigger CaseTrigger on Case (before insert, before update) {
//This only handles the first record in the Trigger.new collection
//But if more than 1 Case initiated this trigger, those additional records
//will not be processed
Case c1 = Trigger.old[0]; // Noncompliant
Case c2 = Trigger.new[0]; // Noncompliant
Case c3 = Trigger.oldmap.get(1); // Noncompliant
Case c4 = Trigger.newmap.get(1); // Noncompliant
// ...
}
Compliant solution
trigger CaseTrigger on Case (before insert, before update) {
List<String> Names = new List<String>{};
//Loop through all records in the Trigger.new collection
for(Case c: Trigger.new){ // Good: Iterate through the trigger.new array instead
c.Subject = c.Number + ':' + c.Status
}
}