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
Clayton HilteClayton Hilte 

Account Trigger to query the next upcoming Event

I am trying to create a trigger that on insert/update of an Account, it will query Events related to the Account and take the Start Date of the next upcoming Event and stick that into a custom field on the Account. I have created the code below, and it looks to fail at line 18. At this line, I am trying to convert "StartDateTime" from a DateTime field to a regular Date field and then use that in the next upcoming event custom field on Account. Any thoughts on this? CODE BELOW!

trigger nextScheduledEvent on Account (after insert, after update) {
    
    List<String> accountIds = new List<String>();
    List<Account> parentAccounts = new List<Account>();
    List<Event> eventDate = new List<Event>();
    
    for ( Account acc : trigger.new ){
        accountIds.add(acc.id);
    }
    
    eventDate = [SELECT StartDateTime
                  FROM Event
                  WHERE StartDateTime >=:system.now()
                  AND AccountId in :accountIds
                  ORDER BY StartDateTime asc
                  LIMIT 1];
    
    Date d = Date.valueof(eventDate.get(0));
    Date nextDate = date.newInstance(d.year(), d.month(), d.day());
    for ( Account a : trigger.new ){
        a.Next_Scheduled_Event__c = nextDate;
    }

}
Clayton HilteClayton Hilte
The Error message I am getting on update of Account is:

Apex trigger nextScheduledEvent caused an unexpected exception, contact your administrator: nextScheduledEvent: execution of AfterUpdate caused by: System.TypeException: Invalid date: [Event (StartDateTime:Wed Oct 28 13:00:00 GMT 2015, Id:00Ue0000002XpurEAC)]: Trigger.nextScheduledEvent: line 18, column 1
srlawr uksrlawr uk
I wrote huge answer then I noticed you missed the date field name on your line for the list get. It should be:
Datetime d = Date.valueof(eventDate.get(0).StartDateTime);