Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Codify trigger logic on related objects #1

Open
YodaDaCoda opened this issue Jun 5, 2020 · 0 comments
Open

RFC: Codify trigger logic on related objects #1

YodaDaCoda opened this issue Jun 5, 2020 · 0 comments

Comments

@YodaDaCoda
Copy link
Member

YodaDaCoda commented Jun 5, 2020

Triggers shouldn't modify other objects - they should perform a DML operation and allow a trigger for the other object to perform the logic.

This keeps logic for any given object with that object and allows for updating that object and applying the relevant logic from anywhere.

Very contrived example (which should be using a trigger handler!):

BAD

trigger naughtyContactTrigger on Contact (after UPDATE) {
    List<Account> updateList = new List<Account>();
    for (Contact c : Trigger.new) {
        if (String.isBlank(c.AccountId)) {
            continue;
        }
        if (c.LastName == 'Testington') {
            updateList.add(new Account(Id=c.AccountId, Name='Testington Account'));
        }
    }
    UPDATE updateList;
}

GOOD

trigger goodContactTrigger on Contact (after UPDATE) {
    List<Account> updateList = new List<Account>();
    for (Contact c : Trigger.new) {
        if (String.isBlank(c.AccountId)) {
            continue;
        }
        updateList.add(new Account(Id=c.AccountId));
    }
    UPDATE updateList;
}
trigger goodAccountTrigger on Account (before UPDATE) {
    Map<Id, Account> accountMap = new Map<Id, Account>([
        SELECT
            Id,
            (SELECT Id, LastName FROM Contacts)
        FROM Account
        WHERE Id IN :Trigger.new
     ]);

    for (Account a : Trigger.new) {
        Account aa = accountMap.get(a.Id);
        for (Contact c : aa.Contacts) {
            if (c.LastName == 'Testington') {
                a.Name = 'Testington Account';
            }
        }
    }
}
@YodaDaCoda YodaDaCoda changed the title Codify trigger logic on related objects RFC: Codify trigger logic on related objects Jun 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant