function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
katebischoffkatebischoff 

trigger to check all account contacts' "email opt out" box when an account type is changed

Can someone help me to develop a trigger to update the email opt out field on all contacts associated with an account when the account type is changed to competitor? Thanks!

sfdcfoxsfdcfox
trigger optOutCompetetors on Account (after update) {
  for(Contact[] ContactsToUpdate:[SELECT Id FROM Contact WHERE HasOptedOutOfEmail = FALSE AND AccountId IN :Trigger.new AND Account.Type = 'Competitor']) {
    update ContactsToUpdate;
  }
}

 

trigger optOutContactCompetitors on Contact (before insert, before update) {
  Set<Id> allAccounts = new Set<Id>();
  Set<Id> competitorAccounts = new Set<Id>();
  for(Contact c:Trigger.new)
    allAccounts.add(c.AccountId);
  allAccounts.remove(null);
  for(Account a:[SELECT Id FROM Account WHERE Type = 'Competitor' AND Id IN :allAccounts])
    competitorAccounts.add(a.Id);
  for(Contact c:Trigger.new)
    if(competitorAccounts.contains(c.AccountId))
      c.HasOptedOutOfEmail = true;
}

This is a two-part solution. The first part checks if the account is a competitor, and if so, will update all contacts not already opted out. The second part will check all contacts that are created or modified, and automatically opt out any contact that belongs to a competitor account. The only scenario not covered here is if a contact is undeleted on a competitor account; this will resolve itself the next time the contact or account is edited.

katebischoffkatebischoff

Sorry, new to triggers. Is this two separate triggers (one in account and one in contact)? Or do they both go in account?

katebischoffkatebischoff

Nvm, I figured out that the first was for accounts and 2nd for contacts...I implemented the triggers and changed an account to competitor and it successfully updated the contacts to "opt-out" but when I added a new contact to the account it did not automatically opt them out. Any ideas?