1
votes

I have an apex trigger (before insert/update) and a helper class to that trigger. The problem is: 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.

And when I create and update a Product object record, the trigger must check the length of the Description field, if the field is longer than 200 characters, I must trim it to 197 characters and add a triple to the end of the line. What am I doing wrong and how should I proceed?

My trigger:

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


}

Trigger helper 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);
            }
        } 
    }

}

2

2 Answers

1
votes

According to your requirements

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.

You aren't doing that.

Change pr.AddedDate__c=system.today(); to

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

Also according to the abbreviate function documentation the parameter it takes is the max length including the 3 elipses.

So change pr.Description__c = pr.Description__c.abbreviate(lengthOfField); to

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

0
votes

To add to Programmatic's answer...

You defined the trigger as before insert, before update. Cool, that's perfect place for doing data validations, field prepopulation... And you'll get save to database for free!

But then this clashes with next line if(Trigger.isUpdate && Trigger.isAfter){. With this setup it'll never fire. Either remove the if completely or (if you think trigger can get more events in future) go with trigger.isBefore && (trigger.isInsert || trigger.isUpdate).

P.S. It's datetime field? So pr.AddedDate__c=system.now(); is better