I have created a trigger and am hopping for suggestions to clean up the trigger, making it more performant.
The reason for this trigger is: The companies' website has a PHP insert, creating Contacts in Salesforce. However, it is possible that the contact already exists in Salesforce. (The current PHP module does not allow for external ids). My solution is to throw a specific error if the Contact email already exists. The error will contain the existing Contact ID.
To throw this error I think a trigger is the best option, and this way a 'duplicate' Contact will not be created and I will be able to send the existing Contact's Id through the error.
The trigger is as follows:
trigger trig_Contact_webToContact on Contact (before insert)
{
//Defining Variables
String errorMsg = 'The email already exists on another Contact ';
List<String>newEmail = new List<String>();
List<Id>newID = new List<String>();
List<Contact> newContacts = [SELECT id, email FROM Contact WHERE ID IN: Trigger.new];
for(Contact newContact:newContacts) //put emails and Ids in a list for use in SELECT
{
newEmail.add(newContact.email);
newID.add(newContact.Id);
}
//List of Contacts that have the same email as inserted
List<Contact> existingContacts = [SELECT id, email FROM Contact WHERE email IN: newEmail AND id NOT IN: newID];
if(existingContacts.size() > 0)
{
for(Contact ContactError:existingContacts)
{
for(Contact insertedContacts:newContacts)
{
if(ContactError.Email == insertedContacts.Email)
{
errorMsg += ContactError.Id;
insertedContacts.addError(errorMsg);
break;
}
}
}
}
}//TRIGGER TRIG_CONTACT_WEBTOCONTACT
This trigger seems like it should work perfectly, but I feel I am repeating a few unnecessary steps. Any help on cleaning it up would be greatly appreciated.