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
Sreelakshmi AsokanSreelakshmi Asokan 

trigger to prevent duplicate contact based on Email

Hi,

I was trying to practice writing trigger to prevent duplicates on contact based on the email. But I am getting an error "System.FinalException: SObject row does not allow errors". Adding my code below, please help me understanding the issue.

public class preventDuplicate {
    public static void duplicatePreventMthd(List<Contact> conList){
        Map<String,Contact> updatedMap = new Map<String,Contact>();
        if(!conList.isEmpty()){
          for(Contact con:conList){
            updatedMap.put(con.Email,con);
        }  
        } 
        
        List<Contact> fetchedContacts =[SELECT Id,Email FROM Contact WHERE Email IN:updatedMap.keySet()];
        if(!fetchedContacts.isEmpty()){
           for(Contact conn:fetchedContacts){
            if(updatedMap.containsKey(conn.Email)){
                conn.Email.addError('Duplicate Contact not allowed');
            }
        } 
        }
        
    }
}
Best Answer chosen by Sreelakshmi Asokan
SubratSubrat (Salesforce Developers) 
Hello Sreelakshmi ,

The error "System.FinalException: SObject row does not allow errors" occurs when you try to add an error to a record that has already been committed to the database. In your code, you are trying to add an error to a fetched contact record that was queried from the database.

Please try with below code :
'
public class preventDuplicate {
    public static void duplicatePreventMthd(List<Contact> conList){
        Map<String,Contact> updatedMap = new Map<String,Contact>();
        if(!conList.isEmpty()){
          for(Contact con:conList){
            updatedMap.put(con.Email,con);
          }  
        } 
        
        List<Contact> fetchedContacts =[SELECT Id,Email FROM Contact WHERE Email IN:updatedMap.keySet()];
        if(!fetchedContacts.isEmpty()){
           for(Contact conn:fetchedContacts){
            if(updatedMap.containsKey(conn.Email)){
                Contact con = updatedMap.get(conn.Email);
                con.Email.addError('Duplicate Contact not allowed');
            }
          } 
        }
    }
}

If it helps please mark this as Best Answer.
Thank you.