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
CosminCCosminC 

Apex Insert Event invitees before trigger action

Hello,

I have an After Insert trigger on Event which uses data from the related EventRelation objects to get the list of invitees and further create an event in Google Calendar.

I am trying to write a test class for this, inserting an event with invitees, however if I first insert the Event and then I insert EventRelation records to create the invitees, my trigger already fires on the Event insertion which will have no invitees at that point. Is there a way to insert the Event directly with invitees? (I can't seem to find a List of WhoId records on the Event object that would be available through Apex on Event insertion).
 
// setup test data
        Account a = new Account();
        a.Name = 'Test account';
        insert a;
        
        List<Contact> contacts = new List<Contact> {new Contact(LastName = 'Test Con1', Email = 'test@test.ro'), new Contact(LastName = 'Test con2', Email = 'test@test.com')};
        insert contacts;
        
	Event e = new Event();
        e.Description = 'Test event description';
        e.Subject = 'Test event subject';
        e.IsAllDayEvent = false;
        e.IsRecurrence = false;
        e.StartDateTime = DateTime.now();
        e.EndDateTime = DateTime.now().addHours(1);
        insert e;
        
// trigger will already fire here, before EventRelation records are inserted.

        EventRelation er1 = new EventRelation();
        er1.EventId = e.Id;
        er1.IsInvitee = true;
        er1.IsWhat = false;
        er1.RelationId = contacts.get(0).Id;
        EventRelation er2 = new EventRelation();
        er2.EventId = e.Id;
        er2.IsInvitee = true;
        er2.IsWhat = false;
        er2.RelationId = contacts.get(1).Id;
        List<EventRelation> ers = new List<EventRelation>{er1, er2};
        insert ers;

Thanks in advance
NitishNitish
Yes you can insert two related records in one time. You can modify the below code as per your requirement but for this you should have one Ext_Id field on parent object. This is what i have done in one of my requirement.
Contact con=new Contact(LastName='Peter');

Account acc=new Account(ExternalID__c=5);
con.Account=acc;

Account accNew=new Account(Name='AccSingleTransaction',ExternalID__c=5);
Database.SaveResult[] results=Database.insert(new SObject[]{accNew,con});

I hope it will solve your problem.

Thanks,
Nitish
CosminCCosminC
I've managed to solve my problem by adding a single Contact id on the Event whoId field, generating one single invitee for the Event, but that was enough to get 100% code coverage and test what I needed.