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
Neha KamraNeha Kamra 

Trigger Error in Trailhead

While creating trigger in Trailhead.,got this error: Challenge Not yet complete... here's what's wrong: 
The trigger logic failed to prevent double booking of a speaker. Please double check the 'RejectDoubleBooking' trigger code.
Here is code:

trigger RejectDoubleBooking on Session_Speaker__c (before insert, before update) {

    //collect ID's to reduce data calls 
    List<Id> speakerIds = new List<Id>();    
    Map<Id,DateTime> requested_bookings = new Map<Id,DateTime>();
    
    //get all speakers related to the trigger
    //set booking map with ids to fill later
    for(Session_Speaker__c newItem : trigger.new) {
        requested_bookings.put(newItem.Session__c,null); 
        speakerIds.add(newItem.Speaker__c);
    }
    
    //fill out the start date/time for the related sessions
    List<Session__c> related_sessions = [SELECT ID, Session_Date__c from Session__c WHERE ID IN :requested_bookings.keySet()];
    for(Session__c related_session : related_sessions) {
        requested_bookings.put(related_session.Id,related_session.Session_Date__c);
    }
    
    //get related speaker sessions to check against
    List<Session_Speaker__c> related_speakers = [SELECT ID, Speaker__c, Session__c, Session__r.Session_Date__c from Session_Speaker__c WHERE Speaker__c IN :speakerIds];
    
    //check one list against the other
    for(Session_Speaker__c requested_session_speaker : trigger.new) {
        DateTime booking_time = requested_bookings.get(requested_session_speaker.Session__c);
        for(Session_Speaker__c related_speaker : related_speakers) {
            if(related_speaker.Speaker__c == requested_session_speaker.Speaker__c &&
               related_speaker.Session__r.Session_Date__c == booking_time) {
                   requested_session_speaker.addError('The speaker is already booked at that time');
               }
        }
    }


}


Thanks,


 
Amit Chaudhary 8Amit Chaudhary 8
Neha KamraNeha Kamra
@Amit : Thanks for your help. But still it is showing the same error..
Yash Gupta (IsimoTech)Yash Gupta (IsimoTech)
You have done the right approach here .... you can make one empty list (list1) and in another list fetch all the speakers name (list 2) and in third list compare both the list and which ever the record is or speaker is left that only can register .