Scenario: We have two custom object Meeting, Guest on Meeting we have field Status (Scheduled, In-Progress, Completed). On Guest we have Meeting lookup. Write logic such as If Meeting Status is ‘Completed’ then we should not able to link Guest to that Meeting.
GuestTrigger
trigger GuestTrigger on cbugs__Guest__c (before insert) {
GuestTriggerHandler handler = new GuestTriggerHandler();
handler.addGuestToMeeting(trigger.new);
}
GuestTriggerHandler - Solution 1
public class GuestTriggerHandler {
public void addGuestToMeeting(List<cbugs__Guest__c> lstGuests) {
// Way 1: Not using Query in loop
Set<Id> meeetingIds = new Set<Id>();
for(cbugs__Guest__c guest: lstGuests) {
meeetingIds.add(guest.cbugs__Meeting__c);
}
Map<Id,cbugs__Meeting__c> mapMeetings = new Map<Id,cbugs__Meeting__c>([Select Id, cbugs__Status__c From cbugs__Meeting__c Where Id in: meeetingIds]);
for(cbugs__Guest__c guest: lstGuests) {
cbugs__Meeting__c meeting = mapMeetings.get(guest.cbugs__Meeting__c);
if(meeting.cbugs__Status__c == 'Completed') {
guest.addError('Meeting is already finished.');
}
}
}
}
GuestTriggerHandler - Solution 2
public class GuestTriggerHandler {
// Way 2 : Here we are using query in look
public void addGuestToMeeting(List<cbugs__Guest__c> lstGuests) {
Set<Id> meeetingIds = new Set<Id>();
for(cbugs__Guest__c guest: lstGuests) {
List<cbugs__Meeting__c> lstMeetings = [Select Id, cbugs__Status__c From cbugs__Meeting__c Where Id=: guest.cbugs__Meeting__c limit 1];
if(lstMeetings[0].cbugs__Status__c == 'Completed') {
guest.addError('Meeting is already finished.');
}
}
}
}