在Salesforce中避免对Trigger中Update的无限循环操作

在Salesforce中避免对Trigger中Update的无限循环操作:

处理Trigger的时候会有这么一个场景:在Trigger中想修改该Object的某些字段的值,那么如果们在程序中再用代码的方式去更新此时的Object的话,就会出现无限循环。

想必大家稍微想一下就会知晓这其中的道理。不多说,直接上段代码,如下所示:

trigger UpdateBookItemTrigger on Book__c (before insert, before update) {

    if(Trigger.isBefore){
        // Preprocessing
        for (Book__c currentBook : trigger.new)
        {
            currentBook.BookPrice__c = 999;    //set new value to the field BookPrice__c

            Date currentDate = Date.today();
            if(currentBook.LastModifiedDate__c == null){
                currentBook.LastModifiedDate__c = currentDate;
            }
            else if(currentBook.LastModifiedDate__c > currentDate){
                currentBook.LastModifiedDate__c = currentDate.addMonths(-12);
            }
            
            //update currentBook;    //if uncomment this line, it will go into an infinite loop
        }    
    }

}

其他的操作如果有类似的情况也请多留意。

原文地址:https://www.cnblogs.com/mingmingruyuedlut/p/3404758.html