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
Nickolaus JohnsonNickolaus Johnson 

Contact Trigger Assistance Needed

Hi Everyone,

I have this trigger where I'd like it to fire before insert, before update. We have 3 emails fields from the NPSP that we'd like the trigger to fire against so that if a new contact is being created, its email address is ran against any possible email within our system so it does not create that record if it finds a match. The 3 fields we have are npe01__HomeEmail__c, npe01__WorkEmail__c, and npe01__AlternateEmail__c. The trigger is working so that if a value is populated within the email field (which happens automatically based on the preferred email selected), and it finds a match, it will throw the error. However, the new email address entered seems to not be running against the email addresses that aren't selected as "preferred". Any ideas how to fix this?

Here is the code:

trigger DupEmail on Contact(before insert, before update) {
  for (Contact myContact: Trigger.new) {

List<Contact> dupes = [SELECT Id FROM Contact WHERE

     (Id != :myContact.Id AND
     Email != null AND
     (Email = :myContact.npe01__WorkEmail__c OR
     Email = :myContact.npe01__AlternateEmail__c OR
     Email = :myContact.npe01__HomeEmail__c))

     ]  
     ;
if (dupes.size() > 0) { String errorMessage = 'Duplicate contact found! '; errorMessage += 'Duplicate record URL = ' + 'https://cs16.salesforce.com' + '/' + dupes[0].Id;
myContact.addError(errorMessage);
} }
  }


Thank you!
Sushil KaushikSushil Kaushik
Hello Nick,

What i can see you have written wrong condition in where clause.  You may change it as below :-


List<Contact> dupes = [SELECT Id FROM Contact WHERE

     (Id != :myContact.Id AND
     Email != null AND
     (Email != :myContact.npe01_WorkEmail__c OR
     Email != :myContact.npe01_AlternateEmail__c OR
     Email != :myContact.npe01_HomeEmail__c))


Regards,

Kaushik