创建一个触发器来验证 Product 对象的数据

Create a trigger that validates the data for the Product object

我有一个顶点触发器(在 insert/update 之前)和该触发器的助手 class。 问题 是:创建对象记录时,触发器应检查 AddedDate 字段是否已填充,如果未填充 - 然后为其分配今天的日期和当前时间。

并且当我创建和更新 Product 对象记录时,触发器必须检查 Description 字段的长度,如果该字段超过 200 个字符,我必须 trim 将其添加到 197 个字符并添加一个三倍到行尾。 我做错了什么,我应该如何处理?

我的触发器:

trigger ProductTrigger on Product__c (before insert, before update) { 
       if(Trigger.isUpdate && Trigger.isAfter){
        ProductTriggerHelper.producthandler(Trigger.new);
    }


}

触发助手class:

public class ProductTriggerHelper {

    public static void producthandler(List<Product__c> products) {
        Schema.DescribeFieldResult F = Product__c.Description__c.getDescribe(); 
        Integer lengthOfField = F.getLength();

        //List<Product__c> prList = new list<Product__c>(); 
        for(Product__c pr: products){

            pr.AddedDate__c=system.today();

            if (String.isNotEmpty(pr.Description__c)) {
               pr.Description__c = pr.Description__c.abbreviate(lengthOfField);
            }
        } 
    }

}

根据您的要求

When creating an object record, the trigger should check if the AddedDate field is filled and if it's not - then assign it today's date and current time.

你没有这样做。

pr.AddedDate__c=system.today();改为

if (pr.AddedDate__c == null) { pr.AddedDate__c=system.today(); }

同样根据abbreviate function documentation,它采用的参数是包括 3 个省略号在内的最大长度。

所以把pr.Description__c = pr.Description__c.abbreviate(lengthOfField);改成

pr.Description__c = pr.Description__c.abbreviate(200);

添加到 Programmatic 的回答中...

您将触发器定义为 before insert, before update。太棒了,那是进行数据验证、现场预填充的完美场所...而且您将免费保存到数据库!

但这与下一行冲突if(Trigger.isUpdate && Trigger.isAfter){。使用此设置,它永远不会开火。完全删除 if 或(如果您认为触发器将来可以获得更多事件)使用 trigger.isBefore && (trigger.isInsert || trigger.isUpdate).

P.S。它是日期时间字段?所以 pr.AddedDate__c=system.now(); 更好