Hey guys, today in this post we are going to learn about How can we prevent duplicate name insert on custom object in Salesforce.
Real time scenarios:- Write a trigger on custom object When a Object (childObjTrigger__c) is being created, if a record exists with the same EmployeeName (EmployeeName__c), the trigger should throw an error.
Create a custom object with custom field name as EmployeeName
Custom Object:- childObjTrigger__c >> custom field:- EmployeeName__c (Text
type)
Files we used in this post example:-
childTriggerhandler.apxt | Apex Class Trigger | It is used for prevent duplicate record creation with same name |
childObjHandler.apxc | Apex Class Handler | It is call into cildTriggerhandler.apxt file. |
Custom Child Object:- childObjTrigger__c Custom Field:- EmployeeName__c |
Custom Child Object with Custom Field | It is custom object with custom field used for display an error if same name being inserted. |
You can download file directly from github by click here
Final Output
Other post that would you like to learn
Step 1:- Apex Class Trigger : childTriggerhandler.apxt
From Developer Console >> File >> New >> Apex Trigger
childTriggerhandler.apxt [Apex Class Trigger]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
trigger childObjTriggerHandler on childObjTrigger__c (before insert, after insert) { if(trigger.isBefore){ if(trigger.isInsert){ system.debug('I am inside before insert'); childObjHandler.childDuplicate(trigger.new); } } else if(trigger.isAfter){ if(trigger.isInsert){ //system.debug('I am inside after insert'); system.debug('Record inserted successfully'); } } } |
Step 2:- Apex Class : childObjHandler.apxc
From Developer Console >> File >> New >> Apex Class
childObjHandler.apxc [Apex Class Handler]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class childObjHandler { //Do not allow duplicate Employee name public static void childDuplicate(List<childObjTrigger__c> dupChildRec){ Set<String> empExtStr = new Set<String>(); List<childObjTrigger__c> empList = [Select Id, Name, EmployeeName__c, childLookup__c, Status__c From childObjTrigger__c where EmployeeName__c !=null]; for(childObjTrigger__c empStr:empList){ empExtStr.add(empStr.EmployeeName__c); } for(childObjTrigger__c childTr:dupChildRec){ if(empExtStr.contains(childTr.EmployeeName__c)){ childTr.EmployeeName__c.addError('Do not allow duplicate'); } } } } |
Other related post that would you like to learn
Trigger is a important topic
good article
I like your article because Trigger is very important topic these days, Please keep sharing
You’re a beautiful inspiration. It really helps me in any situation. Where I stuck. Many of my friends told me to comment there post but I stuck what I should comment. Finally I got your post it always help me. Thanks for the lovely post.
Nice Blog