Hey guys, today in this post we are going to learn about how to write Apex trigger on Account to avoid creation of duplicate record if the account with same phone exists in the system in Salesforce.
A Trigger is a segment of Apex code which executes before or after inserting or modifying a Salesforce record based on the condition provided.
There are different types of triggers based on the action going to be performed. They are Before Triggers and After Triggers. To know more details about Apex Trigger, Click Here.
Final Output β
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
- Find the below steps βΎ
Create Apex Trigger β
Step 1:- Create Apex Trigger : checkDuplicationPhoneAccTrigger.apxt
From Developer Console >> File >> New >> Apex Trigger
checkDuplicationPhoneAccTrigger.apxt [Apex Trigger]
TRIGGER checkDuplicationPhoneAccTrigger ON Account (BEFORE INSERT,after INSERT) {
IF(TRIGGER.isBefore){
system.debug('trigger before trigger');
IF(TRIGGER.isInsert){
set<String> accPhone=NEW set<String>();
FOR(Account a:TRIGGER.new){
accPhone.add(a.Phone);
System.debug('Account phone number is ' +accPhone);
}
set<String> phoneAccData=NEW set<String>();
FOR(Account a:[SELECT Id,Name,Phone FROM Account WHERE Phone IN:accPhone]){
phoneAccData.add(a.Phone);
}
FOR(Account a:TRIGGER.new){
IF(phoneAccData.contains(a.Phone)){
a.addError('Do not allow insert duplicate phone number');
}
}
}
}
ELSE IF(TRIGGER.isAfter){
system.debug('trigger after trigger');
}
}
Further post that would you like to learn in Salesforce
How do you prevent creating duplicate records in Salesforce using trigger?
Preventing duplicate records in Salesforce based on a single field can be achieved using a Set that can store the values of that specific field from all existing records and compare it with the list of new records that are going to be inserted.
How can you prevent duplicate leads from being created?
Block sales reps from creating duplicate leads. In the Standard Lead Duplicate Rule, select Block instead of Allow. With the Standard Lead Duplicate Rule set to block duplicates, a rep can click to view duplicates of leads but can't save a new lead.
What is matching rule and duplicate rule in Salesforce?
Matching rules and duplicate rules work together to ensure that your sales teams work with data that's free of duplicates. Before your reps save new and updated records, matching rules and duplicate rules provide warnings of potential duplicates. You manage matching rules and duplicate rules in Setup.
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 |