function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
himanshu huske 7himanshu huske 7 

sfdc_Trigger_Example

help me with trigger code.
An object has FirstName and LastName field, if we try to create a record with same FristName and LastName, record should not create(throws error).
 
Best Answer chosen by himanshu huske 7
GauravendraGauravendra
You can try something like this:
trigger ExampleTrigger on CustomObj__c (before insert, before update) {

    List<CustomObj__c> listCO = [SELECT Id,FName,LName FROM CustomObj__c];

    for (CustomObj__c a : Trigger.New) {
        for(CustomObj__c dba : listCO) {
            if(a.FName == dba.FName && a.LName == dba.LName ) {
                a.addError('Same Record already existing');
            }
        }
    }
    
}

Hope this helps!

All Answers

GauravendraGauravendra
Hi Himanshu,

I'll suggest you go with Duplicate Rules instead of trigger because as the data grows within your org it will impact the performance.

Just create a matching rule, where it will check for first name and last name.
Create a duplicate rule using that matching rule and you are good to go.
You can choose whether to show alert when a user create a new matching record or just block it from creating.

https://trailhead.salesforce.com/content/learn/modules/sales_admin_duplicate_management/sales_admin_duplicate_management_unit_2

Hope this helps!
himanshu huske 7himanshu huske 7
yes, you r right. but it is for practice purpose, so please help me with code
GauravendraGauravendra
You can try something like this:
trigger ExampleTrigger on CustomObj__c (before insert, before update) {

    List<CustomObj__c> listCO = [SELECT Id,FName,LName FROM CustomObj__c];

    for (CustomObj__c a : Trigger.New) {
        for(CustomObj__c dba : listCO) {
            if(a.FName == dba.FName && a.LName == dba.LName ) {
                a.addError('Same Record already existing');
            }
        }
    }
    
}

Hope this helps!
This was selected as the best answer