Hey guys, today in this post we are going to learn about Write Apex Trigger If Contact is created or updated then we will check associated Account’s Phone, if associated Account has same phone, then we do not allow to create or update contact record, here we will display error message in Salesforce.
Final Output →
Other related post that would you like to learn in Salesforce
Create Apex Trigger →
Step 1:- Create Apex Controller : ContactTrigger.apxt
SFDX:Create Apex Trigger>> New >> ContactTrigger.apxt
ContactTrigger.apxt [Apex Trigger]
TRIGGER ContactTrigger ON Contact (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE) {
IF(TRIGGER.isBefore){
IF(TRIGGER.isInsert){
ContactTriggerHandler.duplicatePhoneHelper(TRIGGER.new);
}ELSE IF(TRIGGER.isUpdate){
ContactTriggerHandler.duplicatePhoneHelper(TRIGGER.new);
}
}ELSE IF(TRIGGER.isAfter){
}
}
Create Trigger Handler Controller →
Step 2:- Create Apex Controller : ContactTriggerHandler.apxc
SFDX:Create Apex Trigger>> New >> ContactTriggerHandler.apxc
ContactTriggerHandler.apxc [Trigger Handler]
public class ContactTriggerHandler {
public static void duplicatePhoneHelper(List<Contact> conList){
Map<string, string> strMap = NEW Map<string, string>();
Set<Id> setId = NEW Set<Id>();
FOR(Contact con:conList){
setId.add(con.AccountId);
}
List<contact> conObjList = [SELECT Id, FirstName, LastName, AccountId, Phone FROM Contact WHERE AccountId IN:setId];
FOR(Contact con2:conObjList){
strMap.put(con2.Phone, con2.AccountId);
}
FOR(Contact con3:conList){
IF(!strMap.isEmpty() && strMap.containskey(con3.Phone)){
con3.addError('Do not allow duplicate record, if associated Account has same phone no');
}
}
}
}
Further post that would you like to learn in Salesforce
How to avoid creating duplicate records in Salesforce?
Another easy way to avoid creating duplicate contacts and leads is to import them via Salesforce's Data Import Wizard. This feature automatically prevents the creation of duplicate records using the record's email address as a unique identifier.
How to prevent duplicate account creation?
A quintessential way to cut down on malicious duplicate accounts is to require users to verify their identities when creating accounts. Sometimes, it may suffice to ask for an e-mail address or phone number, and then require the user to click a link in an email or text message.
How duplicate record is detected in Salesforce?
Duplicates can be detected when a sales rep creates, clones, or edits a record and a duplicate rule runs, or when you run a duplicate job. They can also be detected as part of other processes, such as importing or an API. A duplicate rule alerts a sales rep and lists possible duplicates.
Related Topics | You May Also Like
Our Free Courses →
👉 Get Free Course →
📌 Salesforce Administrators 📌 Salesforce Lightning Flow Builder 📌 Salesforce Record Trigger Flow Builder |
👉 Get Free Course →
📌 Aura Lightning Framework 📌 Lightning Web Component (LWC) 📌 Rest APIs Integration |