Count # Number of active contact on Account record.
Scenario: Calculate #NoOfActiveContact for Account record.
Solution: Create an Apex Trigger on Contact object and calculate for all case (insert, update, delete, undelete)
trigger CountActiveContact on Contact (after insert,after update,after delete,after undelete) {
Set<id> parentId = new Set<Id>(); // AccountId Set
if(Trigger.isAfter){
if(Trigger.isUpdate || Trigger.isInsert || Trigger.isUndelete){
for(Contact con: Trigger.new){ // return list of new sObject record
if(con.accountId !=null){ //check if accountid is not null
parentId.add(con.accountId); //add accountid in set
if(Trigger.isUpdate){ // check for update
if(Trigger.oldMap.get(con.id).AccountId != con.AccountId){ // check old accountid with new
parentId.add(Trigger.oldMap.get(con.id).AccountId);//accountid set
}
}
}
}
}
if(Trigger.isDelete){// delete
for(Contact con: Trigger.old){ // return list of deleted sObject record
parentId.add(con.accountId);
}
}
List<Account> accListForUpdate = new List<Account>(); //account list for update
for(Account acc: [select id,ARI__No_Of_Contact__c,(select id from contacts where isActive__c=true) from Account where id IN: parentId]){
acc.ARI__No_Of_Contact__c = acc.contacts.size(); // get size of contact list on account
accListForUpdate.add(acc); //add acc object in list
}
if(accListForUpdate.size()>0){ //check for list size
try{
update accListForUpdate; // update account list
}
catch(Exception e){
system.debug('Exception has occured! '+e.getMessage());
}
}
}
}
0 comments:
Post a comment