Hello friends, In this example we work on a trigger to check duplicates between two objects.
Lets say we have a custom object called Import Contacts where user creates a new contact with all details. As per the requirement the below apex trigger will do a duplicate check with Contact records to see if there is any Contact with the same first name and last name.
If we find a match in Salesforce Contact record then the user can only create an Import Contacts record else after Import Contacts is created the trigger will auto create Contact record with all the details from Import Contacts.
trigger Trigger_ImportContact on Import_Contact__c (after insert) { List<String> firstName = new List<String>(); List<String> lastName = new List<String>(); for (Import_Contact__c iContact : trigger.new) { firstName.add(iContact.First_Name__c); lastName.add(iContact.Last_Name__c); } List<Contact> contacts = [ SELECT Id, FirstName, LastName, Phone FROM Contact WHERE FirstName IN: firstName AND LastName IN: lastName ]; Set<String> uniqueSet = new Set<String>(); for(Contact con: contacts) { uniqueSet.add(con.FirstName+con.LastName); } List<Contact> insertContacts = new List<Contact>(); for (Import_Contact__c iContact : trigger.new) { if (!uniqueSet.contains(iContact.First_Name__c+iContact.Last_Name__c)) { Contact con = new Contact(); con.FirstName = iContact.First_Name__c; con.LastName = iContact.Last_Name__c; con.Phone = iContact.Phone__c; con.AccountId = iContact.Account__c; con.Email = iContact.Email__c; insertContacts.add(con); } } if (!insertContacts.isEmpty()) { insert insertContacts; } }
Also you can click on this link to get more related programs on Salesforce.
Useful Trailhead Trailmix -> Click here