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
Travis - GHTravis - GH 

Hi all! Iwant to write a trigger to account. I creating an account with Email field to be unique for each account, If the Email is not unique to issue an error and do not secure data - that`s work

trigger AccountEmail on Account (before insert) {

    Map<String, Account> accMap = new Map <String, Account>();
    Map<String, Account> exMap = new Map  <String, Account>();
    Map<String, Contact> conMap = new Map <String, Contact>();
    for(Account account:{
      accMap.put(account.Email__c, account); //
   for(Account acc : [SELECT Name, Email__c, Secondary_Email__c FROM Account WHERE Email__c in: accMap.keySet()]) {
       exMap.put(acc.Email__c, acc);   
    for(Contact con : [SELECT Email, Secondary_Email__c FROM Contact WHERE Secondary_Email__c in : conMap.keySet()]){
        conMap.put(con.Secondary_Email__c, con);
     for(Account acc : {
         if(exMap.containsKey(acc.Email__c)) {


Travis - GHTravis - GH

But then I create a custom field on the Account - Secondary Email object and the same field on the Contact object, For this field I need make a check - If the entered Secondary Email is contained in the Contact object, then issue an error.  In the trigger, consider processing not a single Account, Foresee that there can be several accounts (Process List <Account>) -  doesn`t work,  related list is empty.  What I need to do? Thanks!


    List<Contact> ct = new List <Contact>();

    for(Account acc :{
           Contact con = new Contact(
                    LastName = acc.Name,
                    Secondary_Email__c = acc.Secondary_Email__c,

    insert ct; 

    if (conMap != null && !conMap.isEmpty()){
        for(Contact con : [SELECT Secondary_Email__c FROM Contact WHERE Secondary_Email__c IN : conMap.keySet()]){
            if(con!= null){
                Contact newContact = conMap.get(con.Secondary_Email__c);
                newContact.Secondary_Email__c.addError('contact email exists');