Skip to main content
1 of 3
gNerb
  • 9.6k
  • 5
  • 27
  • 58

The first thing I would say is that you have entirely too many layers of abstraction. This is a problem on a platform when CPU usage is a premium. This also makes troubleshooting issues much more difficult IMO (I'm sure others will have a different opinion however). I'm not going to say what you're doing wont work but I'd advise against it.

Also, you need to bulkify your trigger. Having an insert inside of a for loop is very much against best practices.

The following should work.

Utility Class

public class EventUtils {
    public static isTriggerEnabled = true;
    public static List<EventRelation__c> createEventRelations(List<Event> newEvents) {
        List<EventRelation__c> result = new List<EventRelation__c>();

        for (Event e : newEvents) {
            if (
                // logic to filter out only the events you care about
            ) {
                result.add(new EventRelation__c(
                    EventId__c = e.Id,
                    RelationId__c = e.WhoId
                ));
            }
        }

        return result;
    }
}

Trigger

trigger EventTrigger on Event (before insert, after insert, after update, after delete) {
    switch on triggerEvent {
        when AFTER_INSERT{
            List<EventRelation__c> relations = EventUtils.createEventRelations(Trigger.New);

            if (!relations.isEmpty()) {
                insert relations;
            }
        }
    }
}
gNerb
  • 9.6k
  • 5
  • 27
  • 58