I think this can be accomplished via one quuery and then you will differenciate different records types from it.It's like let's say I have 2 different recordTypes of contacts with name of RT1 and RT2. Now, on account I have two fields which calculates Total_RT1_Contacts__c, and Total_RT2_Contacts__c.In this scenario you can write a trigger on contact object like below, Trigger ContactRTCount On Contact(After Insert, After Update, After Delete, After Undelete){
Set<ID> AccountIds = New Set<ID>();
If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
For(Contact C:Trigger.New){
AccountIds.add(C.AccountID);
}
}
If(Trigger.IsDelete){
For(Contact C:Trigger.Old){
AccountIds.add(C.AccountID);
}
}
List<Account> AccountListToUpdate = New List<Account>();
For(Account act : [Select Id, Total_RT1_Contacts__c, Total_RT2_Contacts__c, (Select Id, RrcordType.Name FROM Contacts) FROM Account WHERE ID = :AccountIds])
{
List<String> totalRT1 = New List<String>();
List<String> totalRT2 = New List<String>();
For(Contact con : act.Contacts)
{
If(con.RecordType.Name == 'RT1')
{
totalRT1.add(con.RecordType.Name);
}
Else If(con.RecordType.Name == 'RT2')
{
totalRT2.add(con.RecordType.Name);
}
}
act.Total_RT1_Contacts__c = totalRT1.Size();
act.Total_RT2_Contacts__c = totalRT2.Size();
AccountListToUpdate.add(act);
}
try{
If(!AccountListToUpdate.isEmpty()){
update AccountListToUpdate;
}
}
Catch(Exception E){
System.Debug('Thrown Exception is: ' + E.getMessage());
}
}
Hope this helps!
1 answer