Tuesday, June 30, 2015

Trigger : Throw an error if we try to update an Account with contacts

Recently I got a requirement on Triggers.Trigger should trow an error if we try to update an Account which contains child contacts.
Update should be successful if Account does not contains any child Contacts.
I felt some how difficulty in writing this trigger by considering governor limits and optimizing the use of collections but I managed to write the trigger successfully.. After writing this trigger I wanted to share it with others and here is the trigger.

trigger AccountsWithContacts on Account (before update) {
    
    Set<Id> accWithContacts = new Set<Id>();
    for(Contact c: [Select Id,Name,AccountId from Contact Where AccountId In: Trigger.NewMap.KeySet()])
    {
        accWithContacts.add(c.AccountId);
    }
    
    for(Account acc:Trigger.New)
    {
        if(accWithContacts.Contains(acc.Id))
            acc.addError('could not update Account with contacts');
    }

}



No comments:

Post a Comment