Avoid Duplicate Fields Using Apex Trigger Salesforce/SFDC Insert/Update Operation/Salesforce Scenario based Apex Trigger

Scenioro:

When user tries to insert /Update Author record 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 Code for Update operation will be bit Tricky.Please pay some extra attention.

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);
    }
    //For Insert Operation
    if(Trigger.isinsert&&Trigger.isbefore){
        for(Author__c acc:Trigger.new){
            if(accmap.get(acc.Author_Email__c)!=null){
                acc.adderror('Email already exists');
            }
        }
    }
    //For Update Operation
    if(Trigger.isupdate&&Trigger.isbefore){
        for(Author__c acc:Trigger.new){
            if((Trigger.oldmap.get(acc.id).Author_Email__c!=acc.Author_Email__c)&&                                           (accmap.get(acc.Author_Email__c)!=null)){
                acc.adderror('Email already exists');
            }
        }
    }

}

We hope you are clear with the process now .

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

Happy Learning☺☺☺

1 comment:

  1. I tried same to object- Configtable, but the trigger is firing always where it should not fire , please help me

    trigger DuplicateCheck on Config_Table__c (before insert,before update) {
    List accList=new List([select Store_Start_Date__c from Config_Table__c]);
    map accmap=new map();
    for(Config_Table__c acc:accList){
    accmap.put(acc.Store_Start_Date__c,acc);
    }
    //For Insert Operation
    if(Trigger.isinsert&&Trigger.isbefore){
    for(Config_Table__c acc:Trigger.new){
    if(accmap.get(acc.Store_Start_Date__c)!=null){
    acc.adderror('Duplicate Start Date,End Date,Business Group,Country and Market are not Allowed');
    }
    }
    }
    //For Update Operation
    if(Trigger.isupdate&&Trigger.isbefore){
    for(Config_Table__c acc:Trigger.new){
    if((Trigger.oldmap.get(acc.id).Store_Start_Date__c!=acc.Store_Start_Date__c)&& (accmap.get(acc.Store_Start_Date__c)!=null)){
    acc.adderror('Duplicate Start Date,End Date,Business Group,Country and Market are not Allowed');
    }
    }
    }

    }

    ReplyDelete