function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MC34MC34 

Modification on current trigger?

Hi, want to modifying this trigger to include only specific records. So basically I have number of contacts for the account shown on account record. This is calculated via the below trigger: There is a custom number field on account Number_of_contacts and the number is pushed via this trigger on account. Now, I have a need where I only need to push number of contacts that are checked (Motivator on Board - a custom checkbox field) on contact records not all contacts. I can make customer number field on account such as "Number of Total MOBs" but I want a trigger to push it. 
 
trigger ContactTickerTrigger on Contact (After insert, After delete, After undelete, After Update) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete  || Trigger.isUpdate){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId);
                   If(Trigger.isUpdate){
                       if(Trigger.oldMap.get(c.Id).AccountId != c.AccountId){
                          parentIdsSet.add(Trigger.oldMap.get(c.Id).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){
        
    }
}


Thank you!!


 
Best Answer chosen by MC34
Christan G 4Christan G 4
Hi Mit, after reviewing the code further, I reverted the if conditions back to what they were originally and applied a filter to where it stated (Line 26):

List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);

Even though we applied the filter in the beginning, when this SOQL query executes, it contained all the contacts that were associated to an account and did not filter the result based on if Motivator_On_Board__c checkbox was checked within those Contacts. Thus, I applied the filter here to ensure that it only picks up those specific contacts. Below is the revised code:

Apex Class:
trigger ContactSumTrigger on Contact (After insert, After delete, After undelete, After Update) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete  || Trigger.isUpdate){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){  
                   parentIdsSet.add(c.AccountId);
                   If(Trigger.isUpdate){
                       if(Trigger.oldMap.get(c.Id).AccountId != c.AccountId){
                          parentIdsSet.add(Trigger.oldMap.get(c.Id).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, Motivator_On_Board__c From Contacts WHERE Motivator_On_Board__c = true ) 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){
        
    }
}
I hope this resolves your issues!
 

All Answers

Christan G 4Christan G 4
Hi Mit, you can easily fulfill this requirement by adding another conditional criteria to all your if statements that state c.AccountId!=null.

Replace everywhere you state if(c.AccountId!=null) with if(c.AccountId!=null && c.Motivator_on_Board__c = true)

Note: I assume that the API for the checkbox was Motivator_on_Board__c but if it isn't please replace it with the correct API from your org.

As a Salesforce Best Practice, I strongly suggest moving the code you have in this trigger to a separate Apex Class. It makes maintanenance of the code much easier. Imagine if in the future, your company requests to add more functionality to the trigger to do some other action. Incorporating that functionality into this trigger would be no easy task and at some point, it'll become very hard to follow as to what is doing what.
MC34MC34
Hi Christan, 
Thanks for the code edit. However, when I am using this code edit it showing the error - Error: Compile Error: Expression cannot be assigned at line 7 column 20

User-added image
Christan G 4Christan G 4

Hi Mit, my apologies. This is a minor typo on my end. Replace the single equal sign with 2 equals. Thus, it should look like this:

if(c.AccountId!=null && c.Motivator_on_Board__c == true)


That should resolve the issue you are having. My apologies again.

MC34MC34
:( Code is not working. This is still showing me the contacts for the accounts not conatcts that are check motivator on board. Where I am wrong. Let me past the edited code again. Do I need to do modification in other areas in code? Like the last line few lines? 

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){ } }​​​​​​​
trigger ContactSumTrigger on Contact (After insert, After delete, After undelete, After Update) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete  || Trigger.isUpdate){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null && c.Motivator_On_Board__c == true){   
                   parentIdsSet.add(c.AccountId);
                   If(Trigger.isUpdate){
                       if(Trigger.oldMap.get(c.Id).AccountId != c.AccountId){
                          parentIdsSet.add(Trigger.oldMap.get(c.Id).AccountId);
                       }
                    }
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Contact c : Trigger.Old){
                if(c.AccountId!=null && c.Motivator_On_Board__c == true){   
                   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){
        
    }
}
MC34MC34
Christan, just for the note the field is on Contact record "Motivator on board". 
Christan G 4Christan G 4
Hi Mit, after reviewing the code further, I reverted the if conditions back to what they were originally and applied a filter to where it stated (Line 26):

List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);

Even though we applied the filter in the beginning, when this SOQL query executes, it contained all the contacts that were associated to an account and did not filter the result based on if Motivator_On_Board__c checkbox was checked within those Contacts. Thus, I applied the filter here to ensure that it only picks up those specific contacts. Below is the revised code:

Apex Class:
trigger ContactSumTrigger on Contact (After insert, After delete, After undelete, After Update) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete  || Trigger.isUpdate){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){  
                   parentIdsSet.add(c.AccountId);
                   If(Trigger.isUpdate){
                       if(Trigger.oldMap.get(c.Id).AccountId != c.AccountId){
                          parentIdsSet.add(Trigger.oldMap.get(c.Id).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, Motivator_On_Board__c From Contacts WHERE Motivator_On_Board__c = true ) 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){
        
    }
}
I hope this resolves your issues!
 
This was selected as the best answer
MC34MC34
This is working. Thank you Christan!
Christan G 4Christan G 4
Anytime Mit! When possible, please choose my post as the best answer and mark it as solved.