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
HoysalaHoysala 

. prevent the creation of duplicate accounts based on email in the system.. please write apex code

Alan DePewAlan DePew
trigger ContactTrigger on Contact (before insert, before update) {
    
    Map<String, Contact> contactMap = new Map<String, Contact>();
    for (Contact Contact : System.Trigger.new) {
    
        if ((Contact.Email != null) &&
                (System.Trigger.isInsert ||
                (Contact.Email != 
                    System.Trigger.oldMap.get(Contact.Id).Email))) {
		    
            if (contactMap.containsKey(Contact.Email)) {
                Contact.Email.addError('Another new Contact has the '
                                    + 'same email address.');
            } else {
                contactMap.put(Contact.Email, Contact);
            }
       }
    }
	
    for (Contact contact : [SELECT Email FROM Contact
                      WHERE Email IN :contactMap.KeySet()]) {
        Contact newContact = contactMap.get(Contact.Email);
        newContact.Email.addError('A Contact with this email '
                               + 'address already exists.');
    }
}

 
Alan DePewAlan DePew
Sorry, this is for Contact. However, you can just change to Account object to do the same.
HoysalaHoysala
Sir Alan Depew am getting error in the above code if i change contact to account, can u please solve it for me? i would be really thankfull. sorry for disturbing you, am new to this so am unable to do this...
Alan DePewAlan DePew
I'll assume you created a new email field on Account called Email__c
 
trigger AccountEmailTrigger on Account (before insert, before update) {
    
    Map<String, Account> AccountMap = new Map<String, Account>();
    for (Account Account : System.Trigger.new) {
    
        if ((Account.Email__c != null) &&
                (System.Trigger.isInsert ||
                (Account.Email__c != 
                    System.Trigger.oldMap.get(Account.Id).Email__c))) {
		    
            if (AccountMap.containsKey(Account.Email__c)) {
                Account.Email__c.addError('Another new Account has the '
                                    + 'same email address.');
            } else {
                AccountMap.put(Account.Email__c, Account);
            }
       }
    }
	
    for (Account Account : [SELECT Email__c FROM Account
                      WHERE Email__c IN :AccountMap.KeySet()]) {
        Account newAccount = AccountMap.get(Account.Email__c);
        newAccount.Email__c.addError('An Account with this email '
                               + 'address already exists.');
    }
}