Development questions
Write a trigger to prevent creating two Booking__c records for the same Room__c with overlapping Start_Date__c and End_Date__c.
Two bookings overlap when newStart < existingEnd AND newEnd > existingStart for the same Room. Check the database and also bookings in the same batch.
apex
trigger BookingTrigger on Booking__c (before insert, before update) {
Set<Id> rooms = new Set<Id>();
for (Booking__c b : Trigger.new) rooms.add(b.Room__c);
List<Booking__c> existing = [SELECT Id, Room__c, Start_Date__c, End_Date__c FROM Booking__c
WHERE Room__c IN :rooms AND Id NOT IN :Trigger.new];
for (Booking__c b : Trigger.new) {
for (Booking__c e : existing) {
if (e.Room__c == b.Room__c && b.Start_Date__c < e.End_Date__c && b.End_Date__c > e.Start_Date__c)
b.addError('Room is already booked for these dates.');
}
for (Booking__c o : Trigger.new) {
if (o != b && o.Room__c == b.Room__c && b.Start_Date__c < o.End_Date__c && b.End_Date__c > o.Start_Date__c)
b.addError('Overlaps another booking in this request.');
}
}
}
For large data, group existing bookings by Room in a Map to avoid O(n²) loops.
apex-triggertriggercodingscenariovalidation
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?