Skip to main content
Hello,

I having been looking around and have not been able to find out if my scenario is feasible with apex coding. 

What I am looking to do via coding

Goal: To update multiple fields on the Case Object from a related Object.

I would like to have a trigger (After Insert,After Delete) that will run a query to give a count total of each record type on the related object and then update the fields on the Case Object. The fields on the Case Object hold the total count of each Record Type. 

I am not sure if this is something I can accomplish with just one query or if I will need to have a query for each field that I want to update. Any reference material or guidance would be much appreciated.

Thanks!
1 answer
  1. Jul 28, 2017, 5:10 PM
    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!

     
0/9000