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
Robby ButteryRobby Buttery 

Trigger to update Checkbox field based on Date Field

Hey all,

Posted about this a while ago, but still never got a real answer. Please help if you can!

We have a Date field in our Contact records - "Date of Training"

We want to build a Checkbox field in the Account level that looks at all of the Contacts related to that Account, and if there is a Contact trained in the past 6 months, then the box will be checked. If there is no Contact in the Account trained in the past 6 months, the Checkbox will be unchecked.

I'm aware this will take APEX code and triggers, just not sure how to approach it

Can anyone help with this?
Lalit Mistry 21Lalit Mistry 21
Hi Robby,

Assuming the custom date field on contact is Date_of_Training__c and checkbox on account as Trained__c, below piece of code in contact trigger (after insert, after update) should work.

Set<Id> accountIds = new Set<Id>();
for(Contact con : Trigger.new){
    accountIds.add(con.AccountId);
}

Date pastSixMonth = System.today().addMonths(-6);
List<Account> acts = [SELECT Id, Trained__c, (SELECT Id FROM Contacts WHERE Date_of_Training__c >= :pastSixMonth) 
                        FROM Account WHERE Id IN :accountIds];
                        
for(Account act : acts){
    if(a.Contacts != null && !a.Contacts.isEmpty()){
        a.Trained__c = true;
    } else {
        a.Trained__c = false;
    }
}
update acts;
Robby ButteryRobby Buttery
Hey @Lalit, would this dynamically change daily? Or is this something that would only update on Save of Accounts/Contacts?