I am have a custom object (VIP) with a master-detail to the Contact object. The custom object has 1 picklist field (Type) and I want to make that field unique for each Contact/VIP record combination. In other words the VIP records can have the same Type value as long as they are linked to different Contacts, but that value can only appear once for each Contact.
I've tried the code below, but it prevents me from entering any value in the type field. I'm sure I'm missing something obvious to do what I need. Ideas?
trigger UpdateVIP on VIP__c (after insert, after update, after delete){
Set<Id> contIds = new Set<ID>();
if (Trigger.isDelete)
{
for(Type__c vip : Trigger.old){
contIds.add(vip.Contact__c);
}
}
else
{
for(Type__c vip : Trigger.new){
contIds.add(vip.Contact__c);
}
}
Set<String> setVIPList = new Set<String>();
for(VIP__c objVIP: [SELECT Contact__c, Type__c
FROM VIP__c
WHERE Contact__c in: contIds]){
setVIPList.add(objVIP.Type__c);
for(VIP__c objVIP2: Trigger.new){
if(setVIPList.contains(objVIP2.Type__c))
{
objVIP2.Type__c.addError('ThisType already exists for this Contact');
}
else
{ Rest of trigger