61 lines
1.7 KiB
Plaintext
61 lines
1.7 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
|
|
|
|
[source,apex]
|
|
----
|
|
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
|
|
|
|
[source,apex]
|
|
----
|
|
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/wiki/apex_code_best_practices[Apex Design Best Practices]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|