50 lines
1.5 KiB
Plaintext
50 lines
1.5 KiB
Plaintext
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
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* https://trailhead.salesforce.com/en/content/learn/modules/apex_triggers/apex_triggers_bulk[Bulk Apex Triggers]
|
|
* https://developer.salesforce.com/page/Best_Practice%3A_Bulkify_Your_Code[Best Practice: Bulkify Your Code]
|
|
|