I am relatively new to building Apex Triggers and need some help.
Trigger's Purpose: The Account Triggers purpose is to throw an error message if there is no contact associated to the Account upon an edit to the Account Record.
Problem I am getting an error message that says "unexpected token: for" on the line that has the for loop for Contact. What is wrong here? Thank you everyone ahead of time.
Below is my Trigger
trigger Account_Contact_Required on Account (before update, after update) {
Set<Id> allAccountIds = new Set<Id>();
Set<Id> AccountwithContactsIds = new Set<Id>();
// fetch all the Account Id's in SFDC and throw in list
for(Account acc : trigger.new)
{
allAccountIds.add(acc.Id);
}
}
// fetch Account Id's that have a Contact associated and throw in list
for(Contact co : [Select AccountId From Contact Where AccountId IN : allAccountIds ])
{
AccountwithContactsIds.add(co.AccountId);
}
// compare the two sets (one has all Account Id's and other has just Account Id's with at least one Contact)
// Left out Accounts should not be allowed to be edited until a Contact is associated with the Account, so we throw an error.
for(Account a : trigger.new)
{
if(allAccountIds.contains(a.Id) && !AccountwithContactsIds.contains(a.Id))
a.addError('At least one contact is required on the Account.');
}
}