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 

Need to update an Account field based on field values in related Contacts

I mark my trained clients with a "trained date" field in the Contact record, and I want to create a checkbox field on the Account level that will check itself if the Account record has an contacts that have been trained in the last 3 months.

I know I will have to make a trigger, I just need to know how I would go about writing it/has someone already written a trigger to help with this
Akshay_DhimanAkshay_Dhiman
Hi Robby,
Below is a code for the same.
Apex Class :
public class CheckTrainedContact { 
    public static void check(List <Contact> cntList){
        set <id> CntId = new set <id>();
        Date date1;
        List <Account> actlist = new List <Account>();
        List <Contact> contlist = new List <Contact>();
        for(Contact cnt :cntList){
            CntId.add(cnt.Id);
        }
        contlist = [select id,Trainned_Date__c,AccountId from Contact where id in: CntId ];
        date1 = contlist[0].Trainned_Date__c;
        system.debug('date1--->'+date1);
        Date date2 = date.today();
        Integer monthDiff = date1.monthsBetween(date2);
        if(monthDiff >= 3){
            for(Contact cnt :contlist){
                Account acc_i = new Account();
                acc_i.id=cnt.AccountId;
                acc_i.Trainned_Contact__c = true;
                actlist.add(acc_i);
            }
            update actlist;
        }
        else{
            for(Contact cnt :contlist){
                Account acc_i = new Account();
                acc_i.id=cnt.AccountId;
                acc_i.Trainned_Contact__c = false;
                actlist.add(acc_i);
                
            }
            update actlist;
       }
    }
}


//Apex Trigger :

trigger ContactTrigger on Contact (before insert , before update ,after insert ,after update) {
   if(Trigger.isafter && Trigger.isinsert){
        CheckTrainedContact.check(Trigger.new);
    }
     else if(Trigger.isafter && Trigger.isupdate){
        CheckTrainedContact.check(Trigger.new);
    }
        
}

Hope It will help you!

Regards,
Akshay
Robby ButteryRobby Buttery
I am getting this error: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactTrigger: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Class.CheckTrainedContact.check: line 14, column 1 Trigger.ContactTrigger: line 3, column 1: []