I am trying to auto create Salesforce Event record when a custom object is created

enter image description here

And here is my code:

trigger CreatePTOEvent on Thrive_HR_PTO_Request__c (after insert) {
// Event is created when PTO Request record is created
List<Event> ptoevents = new List<Event>();
List<Thrive_HR_PTO_Request__c> ptorequest = Trigger.new;

for(Thrive_HR_PTO_Request__c ptr : ptorequest) {

    datetime StartDate = ptr.Start_Date__c;
    datetime EndDate = ptr.End_Date__c;
    date StartDateOnly = StartDate.date(); 
    date EndDateOnly = EndDate.date();

    Integer daysDifference = StartDateOnly.daysBetween(EndDateOnly);

    if(daysDifference < 14) {
        Event evt = new Event(Ownerid=ptr.CreatedById, WhatId=ptr.Id, 
                       EndDateTime=ptr.End_Date__c, ActivityDateTime=ptr.Start_Date__c,

    // add events to record

    else if (daysDifference >= 14) {
        ptr.End_Date__c.addError('You can not exceed more than 14 days');
insert ptoevents;


When I put IsAllDayEvent=true, the even shows up in the related list:

enter image description here

But when I take that out, because I want the Event record to have Date and Time—it creates those records but it doesn't show up in my related record.

enter image description here

What am I doing wrong??

  • did you try to insert an Event in the UI, then query the database values using SFDC Workbench, Developer Console, or Eclipse to see how they compare to the Event you insert through Apex?
    – cropredy
    Sep 10 '14 at 23:18
  • How did you set the Start and End Dates? You only showed the Open Activities related list, they may appear in the Activity History related list.
    – Kevin Lam
    Sep 11 '14 at 2:09

When the end date of an Event passes it is automatically moved to the Activity History related list, unlike Tasks which remain in the Open Activities related list until you close them.

In your first screenshot it shows that you're creating your Event with the current date and time. This means that when you save the record the end date/time has already passed and so it will be in Activity History list and not Open Activities.

Set an end date/time a little way in the future and your Event should show up.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.