
I've been reading about the various options of providing a count of the number of contacts on an account. I may want to develop this further, i.e. number of contacts by status or to put this at the parent account level but small steps.
I have been reading about triggers but I've never created one. I found this which looks good but is erroring, can someone please advise what the problem might be?
I'm in our sandbox as it appears you can't create triggers in the production environment (probably very wise).
I have created an account field named "Number of contacts" which is a number field
I have tried to create this trigger and receive the error message "Compile Error: line 4:0 no viable alternative at character ' ' at line 4 column 0"
Trigger code:
/* Provide summary of Number of Contacts on Account record */
trigger ContactSumTrigger on Contact (after delete, after insert, after undelete,
after update) {
Contact[] cons;
if (Trigger.isDelete)
cons = Trigger.old;
else
cons = Trigger.new;
// get list of accounts
Set<ID> acctIds = new Set<ID>();
for (Contact con : cons) {
acctIds.add(con.AccountId);
}
Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([select Id
,AccountId
from Contact
where AccountId in :acctIds]);
Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id
,Number_of_Contacts__c
from Account
where Id in :acctIds]);
for (Account acct : acctsToUpdate.values()) {
Set<ID> conIds = new Set<ID>();
for (Contact con : contactsForAccounts.values()) {
if (con.AccountId == acct.Id)
conIds.add(con.Id);
}
if (acct.Number_of_Contacts__c != conIds.size())
acct.Number_of_Contacts__c = conIds.size();
}
update acctsToUpdate.values();
}
Use Below code
trigger ContactSumTrigger on Contact (After insert, After delete, After undelete) {
Set<Id> parentIdsSet = new Set<Id>();
List<Account> accountListToUpdate = new List<Account>();
IF(Trigger.IsAfter){
IF(Trigger.IsInsert || Trigger.IsUndelete){
FOR(Contact c : Trigger.new){
if(c.AccountId!=null){
parentIdsSet.add(c.AccountId);
}
}
}
IF(Trigger.IsDelete){
FOR(Contact c : Trigger.Old){
if(c.AccountId!=null){
parentIdsSet.add(c.AccountId);
}
}
}
}
System.debug('#### parentIdsSet = '+parentIdsSet);
List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);
FOR(Account acc : accountList){
List<Contact> contactList = acc.Contacts;
acc.Number_of_Contacts__c = contactList.size();
accountListToUpdate.add(acc);
}
try{
update accountListToUpdate;
}catch(System.Exception e){
}
}