# Trigger, handler, service, selector — copy-able skeleton

Target: Spring '26 (API 66.0). Everything below compiles as written once `Order__c` with `Account__c` (lookup) and `Amount__c` exist. Naming, the 7-event rule and the change-log header follow `salesforce-org-conventions`.

## Trigger (one line, one per object)

```apex
trigger OrderTrigger on Order__c (
    before insert, before update, before delete,
    after insert, after update, after delete, after undelete
) {
    new TriggerTemplateV2().run(new OrderTriggerHandler());
}
```

All **seven** events are declared even though this handler ignores `before delete` — Trigger Hook
relies on the full set being present. Bypass is wired per handler class in the trigger, so one
piece of automation can be disabled without switching off the object.

## Handler — routing only, recursion guard, bypass

```apex
public with sharing class OrderTriggerHandler {
    private static final Set<Id> PROCESSED_AFTER_UPDATE = new Set<Id>();

    public void run() {
        switch on Trigger.operationType {
            when BEFORE_INSERT, BEFORE_UPDATE {
                OrderService.applyDefaults(pricedOrders(), (Map<Id, Order__c>) Trigger.oldMap);
            }
            when AFTER_INSERT {
                OrderService.rollUpToAccounts(withAccount((List<Order__c>) Trigger.new), null);
            }
            when AFTER_UPDATE {
                List<Order__c> fresh = new List<Order__c>();
                for (Order__c o : withAccount((List<Order__c>) Trigger.new)) {
                    if (!PROCESSED_AFTER_UPDATE.contains(o.Id)) { fresh.add(o); PROCESSED_AFTER_UPDATE.add(o.Id); }
                }
                OrderService.rollUpToAccounts(fresh, (Map<Id, Order__c>) Trigger.oldMap);
            }
            when AFTER_DELETE, AFTER_UNDELETE {
                OrderService.rollUpToAccounts(
                    withAccount((List<Order__c>) (Trigger.isDelete ? Trigger.old : Trigger.new)), null);
            }
        }
    }

    // Filter to the records this logic actually operates on. Never hand Trigger.new
    // to a service wholesale — the handler should state its own scope.
    private List<Order__c> withAccount(List<Order__c> records) {
        List<Order__c> scoped = new List<Order__c>();
        for (Order__c o : records) {
            if (o.Account__c != null) { scoped.add(o); }
        }
        return scoped;
    }

    private List<Order__c> pricedOrders() {
        List<Order__c> scoped = new List<Order__c>();
        for (Order__c o : (List<Order__c>) Trigger.new) {
            if (o.Amount__c != null) { scoped.add(o); }
        }
        return scoped;
    }
}
```

## Service — business rules, change detection, one DML

```apex
public with sharing class OrderService {
    public static void applyDefaults(List<Order__c> orders, Map<Id, Order__c> oldMap) {
        for (Order__c o : orders) {
            o.Status__c = o.Status__c ?? 'Draft';           // before context: no DML needed
        }
    }

    public static void rollUpToAccounts(List<Order__c> orders, Map<Id, Order__c> oldMap) {
        Set<Id> accountIds = new Set<Id>();
        for (Order__c o : orders) {
            Order__c old = oldMap?.get(o.Id);
            Boolean changed = old == null || old.Amount__c != o.Amount__c || old.Account__c != o.Account__c;
            if (changed) {
                accountIds.add(o.Account__c);
                if (old?.Account__c != null) { accountIds.add(old.Account__c); }
            }
        }
        accountIds.remove(null);
        if (accountIds.isEmpty()) { return; }

        List<Account> updates = new List<Account>();
        for (AggregateResult ar : OrderSelector.sumAmountByAccount(accountIds)) {
            updates.add(new Account(Id = (Id) ar.get('Account__c'), Total_Order_Amount__c = (Decimal) ar.get('total')));
        }
        Database.update(updates, AccessLevel.USER_MODE);
    }
}
```

## Selector — every SOQL for the object, USER_MODE, bind variables

```apex
public with sharing class OrderSelector {
    public static List<Order__c> selectByIds(Set<Id> ids) {
        return [SELECT Id, Name, Status__c, Amount__c, Account__c FROM Order__c WHERE Id IN :ids WITH USER_MODE];
    }

    public static List<AggregateResult> sumAmountByAccount(Set<Id> accountIds) {
        return [SELECT Account__c, SUM(Amount__c) total FROM Order__c
                WHERE Account__c IN :accountIds AND Status__c != 'Cancelled'
                WITH USER_MODE GROUP BY Account__c];
    }

    /** Dynamic SOQL when the field list or filter is data-driven. */
    public static List<Order__c> selectByStatus(String status, Integer maxRows) {
        String soql = 'SELECT Id, Name FROM Order__c WHERE Status__c = :status LIMIT :maxRows';
        return Database.queryWithBinds(soql, new Map<String, Object>{ 'status' => status, 'maxRows' => maxRows }, AccessLevel.USER_MODE);
    }
}
```

## Notes

- Bypass is wired **per handler class** in the trigger through `TriggerTemplateV2`, not per object, so one handler can be disabled while the rest of the object's automation keeps running. Validation rules and flows use `User.Ignore_Validation_Rules__c` instead. Conventions in `salesforce-org-conventions`.
- The roll-up above is the Apex answer when volumes rule out a Flow roll-up. For master-detail relationships a roll-up summary field needs no code at all.
- If `Order__c` already has record-triggered flows, do not add this trigger: put the roll-up in an after-save flow or move the flows' logic here and retire them. One entry point per object.
- For tests (positive, bulk 200, negative, `runAs`) see the `apex-testing` skill.
