Skip to content

Instantly share code, notes, and snippets.

@joshbirk
Created August 21, 2015 00:03
Show Gist options
  • Save joshbirk/9b4bf2004afc094267fe to your computer and use it in GitHub Desktop.
Save joshbirk/9b4bf2004afc094267fe to your computer and use it in GitHub Desktop.
Bulkified project triggers
trigger RejectDoubleBooking on Session_Speaker__c (before insert, before update) {
//collect ID's in one list to reduce SOQL
List<Id> speakerIds = new List<Id>();
Map<Id,DateTime> requested_bookings = new Map<Id,DateTime>();
//get all speakers related to the trigger
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
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 others
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');
}
}
}
}
trigger SendConfirmationEmail on Session_Speaker__c (after insert) {
//collect ID's in one list of a single SOQL query
List<Id> sessionSpeakerIds = new List<Id>();
for(Session_Speaker__c newItem : trigger.new) {
sessionSpeakerIds.add(newItem.Id);
}
// Retrieve session name and time + speaker name and email address related to ID's
List<Session_Speaker__c> sessionSpeakers =
[SELECT Session__r.Name,
Session__r.Session_Date__c,
Speaker__r.First_Name__c,
Speaker__r.Last_Name__c,
Speaker__r.Email__c
FROM Session_Speaker__c WHERE Id IN :sessionSpeakerIds];
if(sessionSpeakers.size() > 0) {
// Send confirmation email if we know the speaker's email address
Session_Speaker__c sessionSpeaker = sessionSpeakers[0];
if (sessionSpeaker.Speaker__r.Email__c != null) {
String address = sessionSpeaker.Speaker__r.Email__c;
String subject = 'Speaker Confirmation';
String message = 'Dear ' + sessionSpeaker.Speaker__r.First_Name__c +
',\nYour session "' + sessionSpeaker.Session__r.Name + '" on ' +
sessionSpeaker.Session__r.Session_Date__c + ' is confirmed.\n\n' +
'Thanks for speaking at the conference!';
EmailManager.sendMail(address, subject, message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment