I have a trigger on a custom object (Contact_Communication_Method__c) that checks if a Contact already has the specified Communication_Method_Type__c. I am having a hard time changing the logic so that it will not hit any sfdc governor limits. Any help is great. Here's the trigger
trigger ContactCommunicationMethodUniqueType on Contact_Communication_Method__c (before insert, before update) {
string errorMessage = 'This Contact already has this Communication Method Type assigned.';
Map<String, Contact_Communication_Method__c> contactCommunicationMethodMap1 = new Map<String, Contact_Communication_Method__c>();
for (Contact_Communication_Method__c contactCommunicationMethod : System.Trigger.new)
{
if (System.Trigger.isInsert || (System.Trigger.isUpdate &&
(contactCommunicationMethod.Contact__c != System.Trigger.oldMap.get(contactCommunicationMethod.Id).Contact__c
|| contactCommunicationMethod.Communication_Method_Type__c != System.Trigger.oldMap.get(contactCommunicationMethod.Id).Communication_Method_Type__c
)))
{
string communicationMethodTypeId = contactCommunicationMethod.Communication_Method_Type__c;
System.debug('*********************************Communication Method Type Id: '+ communicationMethodTypeId);
List<Contact_Communication_Method__c> dups = [SELECT Contact__c,
Communication_Method_Type__c
FROM Contact_Communication_Method__c
WHERE Contact__c = :contactCommunicationMethod.Contact__c
AND Communication_Method_Type__c = :communicationMethodTypeId];
System.debug('*********************************dups: '+ dups);
System.debug('*********************************dups.size(): '+ dups.size());
if(dups.size() > 0)
{
contactCommunicationMethodMap1.put(contactCommunicationMethod.Communication_Method_Type__c,contactCommunicationMethod);
Contact_Communication_Method__c newContactCommunicationMethod = contactCommunicationMethodMap1.get(contactCommunicationMethod.Communication_Method_Type__c);
newContactCommunicationMethod.Communication_Method_Type__c.addError(errorMessage);
}
}
}
}