以下是错误代码示范
会报错:System.FinalException: Record is read-only Trigger.
trigger MoneyTrigger on Money__c (after insert, after update) {
Date startDay = Date.newInstance(2023,12,26);
if(Trigger.isAfter && Trigger.isInsert){
for (Money__c moneys : Trigger.new){
moneys.totalDays__c = startDay.daysBetween(moneys.Date__c);
}
}
if(Trigger.isAfter && Trigger.isUpdate){
for (Money__c moneys : Trigger.new){
moneys.totalDays__c = startDay.daysBetween(moneys.Date__c);
}
}
}
原因分析:
想在trigger里面更新字段的话,只能在【before】里面进行
Trigger有下面2种:
1.Before:在数据保存进DB之前 更新记录/验证记录
2.After:访问系统设置的字段值(例如记录的 Id 或 LastModifiedDate 字段),并影响其他记录中的更改,例如登录到某表或触发异步事件。需要注意的是,被after trigger触发后的记录是只读的(它们虽然已经写入数据库但是并没有提交到数据库。)
解决方案:
trigger MoneyTrigger on Money__c (before insert, before update) {
Date startDay = Date.newInstance(2023,12,26);
if(Trigger.isBefore && Trigger.isInsert){
for (Money__c moneys : Trigger.new){
moneys.totalDays__c = startDay.daysBetween(moneys.Date__c);
}
}
if(Trigger.isBefore && Trigger.isUpdate){
for (Money__c moneys : Trigger.new){
moneys.totalDays__c = startDay.daysBetween(moneys.Date__c);
}
}
}
参考:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm