I'm learning triggers and need some help with the logic. Election_Position__c looks up to Election__c and Contact objects. A contact can be assigned only one position in an election. In other words, a contact cannot have more than one position in an election. Here's where I got so far:
trigger TestTrigger on Election_Position__c (before insert, before update) {
Map<Id, Set<Id>> electionToWorkersMap = new Map<Id, Set<Id>>();
for(Election_Position__c ep: [SELECT Election__c, Assigned_Worker__c FROM Election_Position__c]){
if(!electionToWorkersMap.containsKey(ep.Election__c)){
electionToWorkersMap.put(ep.Election__c, new Set<Id>());
}
electionToWorkersMap.get(ep.Election__c).add(ep.Assigned_Worker__c);
}
for(Election_Position__c ep : Trigger.new){
if(electionToWorkersMap.containsKey(ep.Assigned_Worker__c)){
ep.addError('The worker already is assigned to this election, please select another election');
}
}
}