Sample Trigger:
In the below trigger, if a Contact is created or updated, the Average_Rating__c field will be updated as average of all Contacts Rating__c under that Account.
trigger RatingAverage on Contact(after insert, after update) {
Map<Id, List<Contact>> AcctCont = new Map<Id, List<Contact>>();
Map<Id, Contact> NewMap = trigger.NewMap;
List<Account> AcctList = new List<Account>();
List<Contact> ContList = new List<Contact>();
Set<ID> AcctIds = new Set<ID>();
for(Contact Con : trigger.New) {
AcctIds.add(Con.AccountId);
}
System.debug(‘Account ids are ‘ + AcctIds);
AcctList = [SELECT Average_Rating__c FROM Account WHERE Id IN : AcctIds];
System.debug(‘Account List is ‘ + AcctList);
ContList = [SELECT Rating__c, AccountId FROM Contact WHERE AccountID IN : AcctIds];
System.debug(‘Contact List is ‘ + ContList);
for(ID TempId : AcctIds) {
List<Contact> TempContList = new List<Contact>();
for(Contact Con : ContList) {
if(Con.AccountId == TempId) {
TempContList.add(con);
}
Contact TempCont = new Contact();
System.debug(‘Contact Id is ‘ + con.Id);
}
AcctCont.put(TempId, TempContList);
}
System.debug(‘Account and contacts are ‘ + AcctCont);
for(Account Acct : AcctList) {
List<Contact> TempContList = new List<Contact>();
Decimal Total = 0;
System.debug(‘Account Id is ‘ + Acct.Id);
TempContList = AcctCont.get(Acct.Id);
for(Contact Con : TempContList) {
Total = Total + Con.Rating__c;
}
Acct.Average_Rating__c = Total/(TempContList.size());
}
Update AcctList;
}