【问题标题】:Trigger is firing two times, but first run is empty?触发器触发了两次,但第一次运行是空的?
【发布时间】:2020-12-03 17:25:06
【问题描述】:

以下触发器触发了两次:

trigger AccountTrigger on Account ( before insert, after insert, before update, after update, before delete, after delete) {

    AccountTriggerHandler handle = new AccountTriggerHandler(trigger.new, trigger.oldMap);
    System.debug('AccountTrigger created a handler instance: ' + handle);
    // Currently the Trigger is firing twice with no obvious reason.
    
  if (Trigger.isBefore) {
    if (Trigger.isInsert) {
      handle.beforeInsert();
    } 
    if (Trigger.isUpdate) {
      // Call handler here!
    }
    if (Trigger.isDelete) {
      // Call handler here!
    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {
      // Call handler here!
    } 
    if (Trigger.isUpdate) {
      // Call handler here!
    }
    if (Trigger.isDelete) {
      // Call handler here!
    }
  }
}

调试结果显示了两个处理程序实例。奇怪的是:第一个好像是空的?怎么可能?

编辑 1: 测试代码:

@isTest
public class AccountTestTest {
@isTest
    public static void testAccountInsert() {
        // Insert an Account
        Account a = new Account(name='TestCustomer');
        insert a;
        
        Account queryAccount = [SELECT Account.id, Account.name FROM Account WHERE Id = :a.Id];
        System.debug('TEST RESULT: ' + queryAccount);
        System.debug('AccountTestTest completed.');
        // Actually test something...
    }
    
}

我知道它缺少断言,但为了简单起见,我只是尝试了这个。

【问题讨论】:

  • 请测试代码?

标签: triggers salesforce apex


【解决方案1】:

这是因为“插入前”。在那个阶段,ids 还没有生成。如果您在插入最佳之前没有任何适合的逻辑(复杂验证?字段预填充?)删除该事件?

【讨论】:

  • 对!需要在前触发器部分检查除 id 之外的其他内容。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2011-09-02
相关资源
最近更新 更多