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
Mateo AlcauterMateo Alcauter 

Trigger to not allow duplicate related records while insert and update

I'm trying to make a trigger so that my Related_Party__c records cannot have both Party_Type_Code__c "Y" and "P"
They can have one or the other, but not both. This trigger currently works, except when I try to update a related party from "Y" to "P" or vise-versa it doesn't let me. How can I fix this so that it does let me update.
 
trigger RelatedPartyTriggers on Related_Party__c (before insert, before update) {
    
   set<String> setName = new set<String>();
   set<String> setExistingName = new set <String>();
    
    for(Related_Party__c party : Trigger.new) {
        setName.add(party.PartyName__c);
    }
    
    for (Related_Party__c party : [select PartyName__c, Party_Type_Code__c From Related_Party__c where PartyName__c in : setName AND Active__c = true AND (Party_Type_Code__c = 'Y' OR Party_Type_Code__c = 'P')]) {
        setExistingName.add(party.PartyName__c);
    }
    
    if(Trigger.isInsert || Trigger.isUpdate)
        for(Related_Party__c p : Trigger.new) {
            if(setExistingName.contains(p.PartyName__c) && (p.Party_Type_Code__c == 'Y' || p.Party_Type_Code__c == 'P') && p.Active__c == true) {
                p.PartyName__c.addError('Cannot be both Y and P');
            }
        }  
}


 
Raj VakatiRaj Vakati
trigger RelatedPartyTriggers on Related_Party__c (before insert, before update) {
    
   set<String> setName = new set<String>();
   set<String> setExistingName = new set <String>();
    
    for(Related_Party__c party : Trigger.new) {
        setName.add(party.PartyName__c);
    }
    
    for (Related_Party__c party : [select PartyName__c, Party_Type_Code__c From Related_Party__c where
	PartyName__c in : setName AND Active__c = true AND (Party_Type_Code__c = 'Y' OR Party_Type_Code__c = 'P')]) {
        setExistingName.add(party.PartyName__c);
    }
    
    if(Trigger.isInsert)
        for(Related_Party__c p : Trigger.new) {
            if(setExistingName.contains(p.PartyName__c) && (p.Party_Type_Code__c == 'Y' || p.Party_Type_Code__c == 'P') && p.Active__c == true) {
                p.PartyName__c.addError('Cannot be both Y and P');
            }
        }  
}

 
Mateo AlcauterMateo Alcauter
That won't work because we have multiple Party_Type__Code_c. We have about 10. So if I  make a related party with the code "S" and another one with code "P", then it will let me update "S" to "Y" which should not let me since that would violate the rule.