Avoid Duplicate Fields Using Apex Trigger Salesforce/SFDC/Salesforce Scenario based Apex Trigger.

Scenario:

When user tries to insert Author with Email which already used in another existing account ,User should be presented with Error 'Email already used by another Author . Please try with another Email'

Apex Trigger:

trigger DemoTrigger on Author__c (before insert,before update) {
    List<Author__c> accList=new List<Author__c>([select Author_Email__c from Author__c]);
    map<String,Author__c> accmap=new map<String,Author__c>();
    for(Author__c acc:accList){
        accmap.put(acc.Author_Email__c,acc);
    }
 
    if(Trigger.isinsert&&Trigger.isbefore){
        for(Author__c acc:Trigger.new){
            if(accmap.get(acc.Author_Email__c)!=null){
                acc.adderror('Email already exists');
            }
        }
    }
}

The above code only works for new records .
Please follow below link to perform the same action for update operation.

Trigger For Update Operation

We hope your clear with the process now .

If you still require further clarifications,Please let us know in the comments .

Happy Learning☺☺☺

2 comments:

  1. The above trigger wont even allow me to create the first record.

    Below is my code which i wrote with the same design as yours. Please check and advice

    trigger preventduplicates on Shift_Worker__c (before insert,before update) {
    List nurseList=new List([select NurseName__c, Phone_Number__c from Shift_Worker__c]);
    map nursemap=new map();
    for(Shift_Worker__c nurse:nurseList){
    nursemap.put(nurse.phone_number__c,nurse);
    }

    if(Trigger.isinsert&&Trigger.isbefore){
    for(Shift_Worker__c nurse:Trigger.new){
    if(nursemap.get(nurse.phone_number__c)!=null){
    nurse.adderror('Phone already exists');
    }
    }
    }
    }

    ReplyDelete
  2. You declared Map without Key, Value pair. How could it is possible.
    map nursemap=new map();

    ReplyDelete