Many times I’ve faced requirements to write a field in a trigger after the record is inserted or update. So, naturally I’ve tried something like this:
But there the record is read only and if you try to change a field value this exception will be fired:
execution of AfterInsert caused by: System.FinalException: Record is read-only
The workaround is quite simple. The object contained by the global trigger.new is read-only, but you can create a new object referring the same ID and change the value that you need.
In addition you have to avoid the recursion since you are changing the record the trigger will be fired again. To avoid that you have to use a static flag which says that the trigger has been already executed during the current executing context.
So, the final code should be like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
trigger changeValueAfter on Account (after insert) {
TriggerHelper.updateValues();
}
public class TriggerHelper {
public static boolean isExecuting = false;
public static void updateValues(){
if( TriggerHelper.isExecuting ){
// if was executed during the same context
// avoid recursion
return;
}
TriggerHelper.isExecuting = true;
//list of new instance of object to update.
Account[] accounts = new Account[]{};
for (Account a: Trigger.new) {
//here the magic by creating a new instance using the same id
Account aux = new Account(Id = a.Id);
aux.Name = a.Id + 'Value forced to be set after by an extrange req';
accounts.add(aux);
}
//then update the new instance list.
update accounts;
}
}
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.