6

I'm wondering if I can write the trigger on Case, that works before and after DML in one file? I have two triggers on Case - first with method working on records before insert, and second for records after insert/update to make relationship.

I know that having two different triggers on the same object isn't a good practisce, so I'm trying now to make one trigger and have order in my code.

What do you think about this? Do you have similar situation in your dev career?

Best regards!

1
  • 1
    Yes, As a best practice there should be a one trigger per object. You can check following link for "Trigger Frameworks and Apex Trigger Best Practices" - developer.salesforce.com/page/…
    – Devendra
    Commented Aug 25, 2016 at 10:31

1 Answer 1

12

It is quite possible, and in fact recommended (if you need trigger logic on both events).

See also:

A common pattern is to have three separate layers of code: the trigger itself, a handler, and a service layer. Here's the trigger framework I prefer.

Trigger

trigger CaseTrigger on Case (after insert)
{
    EventTriggerHandler handle = new EventTriggerHandler(trigger.new, trigger.oldMap);

    if (trigger.isBefore)
    {
        if (trigger.isInsert) handle.beforeInsert();
        if (trigger.isUpdate) handle.beforeUpdate();
        // etc
    }
    if (trigger.isAfter)
    {
        if (trigger.isInsert) handle.afterInsert();
        if (trigger.isUpdate) handle.afterUpdate();
        // etc
    }
}

Handler

public with sharing class EventTriggerHandler
{
    @TestVisible static Boolean bypassTrigger = false;

    final List<Event> newRecords;
    final Map<Id, Event> oldMap;
    public EventTriggerHandler(List<Event> newRecords, Map<Id, Event> oldMap)
    {
        this.newRecords = newRecords;
        this.oldMap = oldMap;
    }

    public void beforeInsert()
    {
        if (bypassTrigger) return;

        CaseService.doStuff1();
    }
    public void afterInsert()
    {
        if (bypassTrigger) return;

        CaseService.doStuff2();
    }

    public void beforeUpdate()
    {
        if (bypassTrigger) return;

        CaseService.doStuff1();
    }
    public void afterUpdate()
    {
        if (bypassTrigger) return;

        CaseService.doStuff3();
    }
}

Service

public with sharing class CaseService
{
    public static void doStuff1() { /* "how" implementation */ }
    public static void doStuff2() { /* "how" implementation */ }
    public static void doStuff3() { /* "how" implementation */ }
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .