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
BaguiarBaguiar 

Trigger to find event dates already taken for other events

Hello there,

 

I'm trying to get this trigger to work and for the part that  updates the Lead fields based on the Event data, is working fine. What I need to add is that if the Event Start date (startdatetime) that is being created/edited matches (same date same time and same ownerID) an Event already saved for the same Owner (Assigned to), an error on the page would display and the Leads would NOT get updated.

 

In other words, I'm trying to avoid an user booking an event that he/she already have another event scheduled on the same date. IF so, the new event date won;t be saved and the fields on the lead will NOT get updated. Here is my code (or the attempts..lol):

 

trigger tourchangeschedule1 on Event (before insert, after update) {
    
    Set<Id> recordIds = new Set<Id>();
    Set<id> eventidhold = New Set<id>();
    Set<id> ownertour = New set<id>();
    Set<string> tdate = New Set<string>();
    
    for ( Event  t : Trigger.New ) {
        if(t.subject=='tour' && t.Stages__c <> '30 days' && t.Stages__c <> '60 days'){
            recordIds.add(t.whoid);
            eventidhold.add(t.Id);
        ownertour.add(t.ownerid);
        tdate.add(t.startdatetime);

        }
    }
    
    List<Event> tourtaken = [select id from event where ownerid in :ownertour and startdatetime = :tdate];
    for ( Event  J : Trigger.New ) {
    IF (tourtaken.size()>0){ 
    a.adderror('There is a tour already scheduled for that time');
    }
    }
    
 
}
    
    List<lead> leadsOfEvents = [select id from lead where id in :recordIds];

    Map < Id ,lead > leadmap = new Map < Id , lead >();

    for ( lead  l : leadsOfEvents   ) {
        leadmap.put( l.Id, l);
    }

    List < lead > leadsToUpdate = new List < lead >();
     
    for(Event e: Trigger.New) {
        lead lc = leadmap.get( e.WhoID );
            
        if ( lc == null ) {
            
            continue;
        }
        
        lc.sales_cycle__C = 'Tour Scheduled';
        lc.tour_scheduled__C = e.StartDateTime;
        leadsToUpdate.add(Lc);
        
    }

    upsert leadsToUpdate;       

}

 

as usual, thanks for the good help!

B