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
Prasanth RPrasanth R 

prevent duplicate records in accounts by using handler class

scenario: how do prevent the duplicate record:

already i tried in list it workedmfor my practice i am trying map.i facing problem kindly someone help me

handler class:
 public static void preventDuplicate1(Map<Id,Account> recmap){
         Map<Id,Account> mapacc =  new Map<Id,Account>([select Id,Name from Account where Name =:recmap.values().Name]);
         system.debug(mapacc.values());
         for(Account acc:mapacc.values()){
             
             if(acc.name != recmap.get(acc.Id).Name){
                 acc.Name.addError('cannot use the rename');
             }
         }
             }


trigger :
trigger AccountDescription on Account (before insert,before update,after insert,after update,before delete,after delete,after undelete) {
if(Trigger.IsBefore && Trigger.IsInsert){
        AccoutBeforeInsert.preventDuplicate1(Trigger.newMap);
    }

can anyone help this?


User-added image

User-added image

User-added image

 

CharuDuttCharuDutt
Hii Prasanth
Try Below Code
trigger PreventDuplicateAccounts on Account (before insert,before update) {
    if(trigger.isAfter){
        if(trigger.isInsert){
            NumberOfChildTriggerHandler2.insertMethod(trigger.new);
        }else if(trigger.isUpdate){
            NumberOfChildTriggerHandler2.updateMethod(trigger.new,trigger.oldMap);
        }
    }
}



public class NumberOfChildTriggerHandler2 {

    public static Void InsertMethod(list<Account> lstAcc ){
       Set <String> NameSet = new Set<String>(); 

    for (Account Acc:trigger.new) {
		if(Acc.Name != null){        
			NameSet.add(Acc.Name);
		}    
    }
    List <Account> AccountList = [SELECT Name FROM Account WHERE Name IN :NameSet];

    for (Account Acc:trigger.new) {
        If (AccountList) {
            
          Acc.Name.adderror( 'Duplicate Account Found. Rename The Account' );
            
        }
      }
    }

    public static Void UpdateMethod(list<Account> lstAcc,map<Id,Account>oldmap ){
        Set <String> NameSet = new Set<String>(); 

    for (Account Acc:trigger.new) {
		if(Acc.Name != null && Acc.Name != oldMap.get(Acc.Id).Name ){        
			NameSet.add(Acc.Name);
		}    
    }
    List <Account> AccountList = [SELECT Name FROM Account WHERE Name IN :NameSet];

    for (Account Acc:trigger.new) {
        If (AccountList) {
            
          Acc.Name.adderror( 'Duplicate Account Found. Rename The Account' );
            
        }
      }
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You