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
Michael Hedrick 2Michael Hedrick 2 

Set Contact as primary if one does not exist

Hello All,
I have the following code that only allows a single Primary Contact per Account.  But what I would like to do is set the newly created Contact as Primary(Primary__c==True) if one does not exist.  Can I utilize my existing Class or do I have to create a new one
Thank you for your time and help.
M
public without sharing class ContactTrgHandler 
{
  public static void onBeforeInsert(List<Contact> trgNew)
  {
    Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
    for(Contact c : trgNew)
    {
      if(String.isNotEmpty(c.AccountId) && c.Primary__c)
      {
        if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
          accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
        accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
      }      
    }
    if(!accountIdToNewContactRtMap.isEmpty())
    {
      Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
      {
        existingContactRtMap.put(a.Id,new Set<Id>());
        for(Contact c : a.Contacts)
          existingContactRtMap.get(a.Id).add(c.RecordTypeId);
      }
      for(Contact c : trgNew)
      {
        if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
          c.addError('There is already a primary contact for this record type.');
      }
    }
  }
  public static void onBeforeUpdate(List<Contact> trgNew,Map<Id,Contact> oldMap)
  {
    Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
    for(Contact c : trgNew)
    {
      if(String.isNotEmpty(c.AccountId) && c.Primary__c && !oldMap.get(c.Id).Primary__c)
      {
        if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
          accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
        accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
      }
    }
    if(!accountIdToNewContactRtMap.isEmpty())
    {
      Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
      {
        existingContactRtMap.put(a.Id,new Set<Id>());
        for(Contact c : a.Contacts)
          existingContactRtMap.get(a.Id).add(c.RecordTypeId);
      }
      for(Contact c : trgNew)
      {
        if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
          c.addError('There is already a primary contact for this record type.');
      }
    }
  }
}

 
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri

Check this

if(!accountIdToNewContactRtMap.isEmpty())
    {
      Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT Id, Id FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
      {
        existingContactRtMap.put(a.Id,new Set<Id>());
        for(Contact c : a.Contacts)
          existingContactRtMap.get(a.Id).add(c.RecordTypeId);
      }
      for(Contact c : trgNew)
      {
        if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
        {
          c.addError('There is already a primary contact for this record type.');
        } else {
            Account a = new Account();
            a.Id = c.AccountId;
            a.PrimaryContact__c = c.Id;
            accountToUpdate.add(a);
        }
      }
      update accountToUpdate;
    }
Neetu_BansalNeetu_Bansal
Hello Michael,

You can try below code, which will also update the primary contact in case of insert, update and delete. Apex trigger is like:
trigger PrimaryContactTrgr on Contact (after insert, after update,after delete) {
    // Assign values of trigger new list to helper class variable
    PrimaryContactHelper.newContactsList = trigger.new;
     // Assign values of trigger old list to helper class variable
    PrimaryContactHelper.oldContactsList = trigger.old;
    // Assign values of trigger new map to helper class variable
    PrimaryContactHelper.newContactsMap = trigger.newMap;
    // Assign values of trigger old map to helper class variable
    PrimaryContactHelper.oldContactsMap = trigger.oldMap;
    if(trigger.isAfter)
    {
      //insert trigger
        if(trigger.isInsert)
        {
          //calling helper class method 
            PrimaryContactHelper.primaryContactactive();
        }
        //update trigger
        if(trigger.isUpdate)
        {
          //calling helper class method
            PrimaryContactHelper.updateContact();
        }
         if(trigger.isDelete)
         {
          //calling helper class method
            PrimaryContactHelper.deleteContact();
         }
     
   }
}
Helper Class:
public with sharing class PrimaryContactHelper 
{
    // List to store contacts of trigger.new
    public static List<Contact> newContactsList = new List<Contact>();
    // List to store contacts of trigger.old
    public static List<Contact> oldContactsList = new List<Contact>();
    // Map to store contacts of trigger.newMap
    public static Map<Id, Contact> newContactsMap = new Map<Id, Contact>();
    // Map to store contacts of trigger.oldMap
    public static Map<Id, Contact> oldContactsMap = new Map<Id, Contact>();

    /**
     * Name: Primary Contact 
     * @param:
     * @return: 
     * Desc: To find active primary contact.
        **/ 
    public static void primaryContactactive()
    {
        set<id> contacts=new set<id>();
        for(contact c:newContactsList)
        {
                contacts.add(c.AccountId);
        }
        
        // Map to store Account list
       Map<Id,Account> accntlist=new Map<Id,Account>([Select Id, PrimaryContact__c,Secondary_Contact__c from Account where Id IN :contacts]);
    for(Contact c:newContactsList)
    {
        if(c.Active_Contact__c)
        {
          if(c.AccountId!=null)
          {
            //Assignment of primary contact to secondary contact
            accntlist.get(c.AccountId).Secondary_Contact__c=accntlist.get(c.AccountId).PrimaryContact__c;
            accntlist.get(c.AccountId).PrimaryContact__c=c.Id;
          } 
        }
      /**  else
        {
            if( accntlist.get(c.AccountId).PrimaryContact__c==c.Id )
        
            {
                accntlist.get(c.AccountId).PrimaryContact__c =accntlist.get(c.AccountId).Secondary_Contact__c;
                accntlist.get(c.AccountId).Secondary_Contact__c=null;
            }
            else if(accntlist.get(c.AccountId).Secondary_Contact__c==c.Id)
            {
                accntlist.get(c.AccountId).Secondary_Contact__c=null;
            }
        }**/
     }
                    update accntlist.values();
    }
    
    /**
     * Name:Update Primary Contact 
     * @param:
     * @return: 
     * Desc: To find active primary contact when update.
        **/ 
    public static void updateContact()
    {
        
        set<id> ids=new set<id>();
        //iteration of contacts
        for(Contact c:newContactsList) 
        {
            if(oldContactsMap.get(c.Id).AccountId != c.AccountId || oldContactsMap.get(c.Id).Active_Contact__c!= c.Active_Contact__c)
            {
                ids.add(c.AccountId);
                ids.add( oldContactsMap.get(c.Id).AccountId);
            }
        }
        // Map to store Account list
        Map<Id,Account> accntlist=new Map<Id,Account>([Select Id,PrimaryContact__c,Secondary_Contact__c  from Account where Id IN : ids]);
        //iterate on new contactslist
        for(Contact c:newContactsList)
        {
          //Check the old map and new map
            if(oldContactsMap.get(c.Id).Active_Contact__c != c.Active_Contact__c|| oldContactsMap.get(c.Id).AccountId != c.AccountId)
            {
                if(c.Active_Contact__c)
                {
                    //Assignment of primary contact to secondary contact
                    accntlist.get(c.AccountId).Secondary_Contact__c=accntlist.get(c.AccountId).PrimaryContact__c;
                   accntlist.get(c.AccountId).PrimaryContact__c=c.Id;
                    /**  if(oldContactsMap.get(c.Id).AccountId != c.AccountId)
                       {
                         if(accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c==c.Id)
                         {
                           accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c = null;
                         }
                       else
                       {
               
                          accntlist.get(oldContactsMap.get(c.Id).AccountId).PrimaryContact__c = accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c;
                          accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c = null;
                       }  
                     
                       }**/
                      
                   }
                else
                {
                     if( accntlist.get(c.AccountId).PrimaryContact__c==c.Id )
                     {
                         accntlist.get(c.AccountId).PrimaryContact__c =accntlist.get(c.AccountId).Secondary_Contact__c;
                         accntlist.get(c.AccountId).Secondary_Contact__c=null;
                           //Check the old contact account id and new contact id
                           if(oldContactsMap.get(c.Id).AccountId != c.AccountId)
                           {
                             if(accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c==c.Id)
                           {
                         
                             accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c = null;
                           }
                           else
                           {
                            accntlist.get(oldContactsMap.get(c.Id).AccountId).PrimaryContact__c = accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c;
                              accntlist.get(oldContactsMap.get(c.Id).AccountId).Secondary_Contact__c = null;
                           }  
                           }
                     }
                      if(accntlist.get(c.AccountId).Secondary_Contact__c==c.Id)
                     {
                           accntlist.get(c.AccountId).Secondary_Contact__c=null;
                           if(oldContactsMap.get(c.Id).AccountId != c.AccountId)
                           {
                             accntlist.get(oldContactsMap.get(c.Id).AccountId ).PrimaryContact__c= accntlist.get(oldContactsMap.get(c.Id).AccountId ).Secondary_Contact__c ;
                             accntlist.get(oldContactsMap.get(c.Id).AccountId ).Secondary_Contact__c= null; 
                           }
                     }
                    
                }
            }
        }
        update accntlist.values();
    }
    /**
     * Name:Delete Primary Contact 
     * @param:
     * @return: 
     * Desc: To Delete primary contact.
        **/ 
    public static void deleteContact()
    {
        
        set<id> ids=new set<id>();
        for(Contact c:oldContactsList)
        {
                ids.add(c.AccountId);
        }
        // Map to store Account list
        Map<Id,Account> accntlist=new Map<Id,Account>([Select Id,PrimaryContact__c,Secondary_Contact__c from Account where Id IN : ids]);
        
       for(Contact c : oldContactsList)
        {
             if(c.Active_Contact__c)
             {
             system.debug('@@@@@@@@@@@@@@@@@@@@@@@@@'+ accntlist.get(c.AccountId).PrimaryContact__c);
             system.debug('@@@@@@@@@@@@@@@@@@@@@@@@@'+ c.Id );
             system.debug('@@@@@@@@@@@@@@@@@@@@@@@@@'+ accntlist.get(c.AccountId).Secondary_Contact__c);
                     if( accntlist.get(c.AccountId).PrimaryContact__c ==null)
                     {
                        accntlist.get(c.AccountId).PrimaryContact__c=accntlist.get(c.AccountId).Secondary_Contact__c;
                         accntlist.get(c.AccountId).Secondary_Contact__c=null;
                     }
             
                     else if(accntlist.get(c.AccountId).Secondary_Contact__c ==null)
                     { 
                        accntlist.get(c.AccountId).Secondary_Contact__c=null;
                    }
            }
        }  
        //update the values
         update accntlist.values();
    }    
   }
Hope this helps you.

Thanks,
Neetu
Michael Hedrick 2Michael Hedrick 2
Thank you both for your replies.  I hope you both had a good holiday.  Neetu I have a question about the helper class.  Do I need to add add new custom fields? I see the following fields; PrimaryContact__c,Secondary_Contact__c,Active_Contact__c.

Bhaswanthnaga, I will modify my existing code as you suggested and let you know how it works.

Thnaks again to you both.
M
Michael Hedrick 2Michael Hedrick 2
Bhaswanthnaga,
Is the syntax below correct?
 [SELECT Id,(SELECT Id, Id FROM Contacts WHERE Primary__c=true)

Also, do I need to create a new field on the Account Object? PrimaryContact__c?

Thanks
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri

sorry that was [SELECT Id,(SELECT Id, recordtypeId FROM Contacts ..............

Yes, you have to create a new field if you want to maintain PC informaiton on Account

Michael Hedrick 2Michael Hedrick 2
Thnaks Bhaswanthnaga,  is 'accountToUpdate' supposed to be  anew list?
Cheers,
M
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
Yes
Michael Hedrick 2Michael Hedrick 2
Hey Bhaswanthnaga,
What would the list look like? And where would I insert the code since this has an Else statement? 
  
Map<Id,Set<Id>> NewContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT Id, recordtypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id Not In :accountIdToNewContactRtMap.keySet()])

Thanks,
M
Michael Hedrick 2Michael Hedrick 2
Still having an issue:
Variable does not exist: ac    - line 34 
Variable does not exist: newContactRtMap   - line 38

Any help is appreciated.
public without sharing class ContactTrgHandler 
{
   public static void onBeforeInsert(List<Contact> trgNew)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }           
        }
      if(!accountIdToNewContactRtMap.isEmpty())
    {
      Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT Id, recordtypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
      {
        existingContactRtMap.put(a.Id,new Set<Id>());
        for(Contact c : a.Contacts)
        existingContactRtMap.get(a.Id).add(c.RecordTypeId);
      }
      for(Contact c : trgNew)
      {
        if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
        {
          c.addError('There is already a primary contact for this record type.');
        } else {
                  Map<Id,Set<Id>> newContactRtMap = new Map<Id,Set<Id>>();
            	  for(Account ac : [SELECT Id,(SELECT id,email,RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id not in :accountIdToNewContactRtMap.keySet()])
                
                  ac.Primary_Contact_Email_Address__c = ac.Contacts[0].email;
                  newContactRtMap.add(ac);
        	}
      }
    
      			update newContactRtMap;   
        }
    }        
    public static void onBeforeUpdate(List<Contact> trgNew,Map<Id,Contact> oldMap)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c && !oldMap.get(c.Id).Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                    accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }
        }
        if(!accountIdToNewContactRtMap.isEmpty())
        {
            Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
            for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
            {
                existingContactRtMap.put(a.Id,new Set<Id>());
                for(Contact c : a.Contacts)
                existingContactRtMap.get(a.Id).add(c.RecordTypeId);
            }
            for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                c.addError('There is already a primary contact for this record type.');
            }
        }
    }
}

 
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
public without sharing class ContactTrgHandler
{
    public static void onBeforeInsert(List<Contact> trgNew)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        Map<Id,Account> newAccountRtMap = new Map<Id,Account>();

        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                    accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }
        }
        if(!accountIdToNewContactRtMap.isEmpty())
        {
            Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
            for(Account a : [SELECT Id,(SELECT Id, recordtypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
            {
                existingContactRtMap.put(a.Id,new Set<Id>());
                for(Contact c : a.Contacts)
                    existingContactRtMap.get(a.Id).add(c.RecordTypeId);
            }
            for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                {
                    c.addError('There is already a primary contact for this record type.');
                } else {
                    for(Account ac : [SELECT Id,(SELECT id,email,RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id not in :accountIdToNewContactRtMap.keySet()])
                    {
                        ac.Primary_Contact_Email_Address__c = ac.Contacts[0].email;
                        newAccountRtMap.add(ac.Id, ac);
                    }

                }
            }
            if(!newAccountRtMap.isEmpty()) {
                update newAccountRtMap.values();
            }

        }
    }
    public static void onBeforeUpdate(List<Contact> trgNew,Map<Id,Contact> oldMap)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c && !oldMap.get(c.Id).Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                    accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }
        }
        if(!accountIdToNewContactRtMap.isEmpty())
        {
            Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
            for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
            {
                existingContactRtMap.put(a.Id,new Set<Id>());
                for(Contact c : a.Contacts)
                    existingContactRtMap.get(a.Id).add(c.RecordTypeId);
            }
            for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                    c.addError('There is already a primary contact for this record type.');
            }
        }
    }
}

Use the above code
Michael Hedrick 2Michael Hedrick 2
Thanks Bhaswanthnaga.
I am getting an error at line 35.  ' newAccountRtMap.add(ac.Id, ac); '
Do we need to include the ac.id?
 
Michael Hedrick 2Michael Hedrick 2
error is:
Method does not exist or incorrect signature: void add(Id, Account) from the type Map<Id,Account>
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
use newAccountRtMap.put(ac.Id,ac)
Michael Hedrick 2Michael Hedrick 2
Hey Bhaswanthnaga.  That fixed the error but the code did not work as expected and I know why but not sure how to corret.t
} else {
                    for(Account ac : [SELECT Id,(SELECT id,email,RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id not in :accountIdToNewContactRtMap.keySet()])
                    {
                        ac.contacts[0].Primary__c=true;
                        ac.Primary_Contact_Email_Address__c = ac.Contacts[0].email;
                        newAccountRtMap.put(ac.Id,ac);
                    }

If there is not a Primary Contact for an Account and a user creates a contact.  That contact needs to be the set as the Primary.  Which means even if the user does not select the checkbox I nned to select the Primary checkbox and make the newly created Contact the Primary Contact.
The code as it stands is only looking for Contacts where the Primary is already checked and this may not be the case.  If you have any other thoughts let me know.  Thnaks for all your help.

Michael 
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri

Not sure why have you changed the code that I have kept in first place please use that code.

else {
           c.Primary_c = true;
            Account a = new Account();
            a.Id = c.AccountId;
            a.PrimaryContact__c = c.Id;
            accountToUpdate.add(a);
            newAccountRtMap.put(ac.Id,ac);

         }
Michael Hedrick 2Michael Hedrick 2
Apologies.  Trying to make too make corrections at once.  So take out the 
for(Account ac : [SELECT Id,(SELECT id,Primary_c,email,RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id not in :accountIdToNewContactRtMap.keySet()])

 
Michael Hedrick 2Michael Hedrick 2
What type of field is  a.PrimaryContact__c?
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
sorry that is ac.Primary_Contact_Email_Address__c  = c.email;
Michael Hedrick 2Michael Hedrick 2
No worries.  You're trying to help and I am trying to understand.
So the for loop stys correct?

for(Account ac : [SELECT Id,(SELECT id,email,RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id not in :accountIdToNewContactRtMap.keySet()])
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
NO for loop wont't stay in the else part just use the code what I have kept 
for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                {
                    c.addError('There is already a primary contact for this record type.');
                } else {
                   
                        c.Primary_c = true;
            Account a = new Account();
            a.Id = c.AccountId;
           ac.Primary_Contact_Email_Address__c  = c.email;
            newAccountRtMap.put(ac.Id,ac);
                   

                }
            }
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
Is it working now ?
Michael Hedrick 2Michael Hedrick 2
Ok
Here is what I have with your recommendations:
public without sharing class ContactTrgHandler 
{
   public static void onBeforeInsert(List<Contact> trgNew)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        Map<Id,Account> newAccountRtMap = new Map<Id,Account>();

        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                    accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }
        }
        if(!accountIdToNewContactRtMap.isEmpty())
        {
            Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
            for(Account a : [SELECT Id,(SELECT Id, recordtypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
            {
                existingContactRtMap.put(a.Id,new Set<Id>());
                for(Contact c : a.Contacts)
                    existingContactRtMap.get(a.Id).add(c.RecordTypeId);
            }
            for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                {
                    c.addError('There is already a primary contact for this record type.');
                } else {
                   
                        c.Primary_c = true;
            Account a = new Account();
            a.Id = c.AccountId;
           ac.Primary_Contact_Email_Address__c  = c.email;
            newAccountRtMap.put(ac.Id,ac);
                   

                }
            }
            }
            if(!newAccountRtMap.isEmpty()) {
                update newAccountRtMap.values();
            }

        }
    }
    public static void onBeforeUpdate(List<Contact> trgNew,Map<Id,Contact> oldMap)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c && !oldMap.get(c.Id).Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                    accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }
        }
        if(!accountIdToNewContactRtMap.isEmpty())
        {
            Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
            for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
            {
                existingContactRtMap.put(a.Id,new Set<Id>());
                for(Contact c : a.Contacts)
                    existingContactRtMap.get(a.Id).add(c.RecordTypeId);
            }
            for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                    c.addError('There is already a primary contact for this record type.');
            }
        }
    }
}

Errors:
Variable does not exist: Primary_c
Variable does not exist: ac
Missing '<EOF>' at 'public'

Are these {} issues? 

 
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
public without sharing class ContactTrgHandler
{
    public static void onBeforeInsert(List<Contact> trgNew)
    {
        Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
        Map<Id,Account> newAccountRtMap = new Map<Id,Account>();

        for(Contact c : trgNew)
        {
            if(String.isNotEmpty(c.AccountId) && c.Primary__c)
            {
                if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                    accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
                accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
            }
        }
        if(!accountIdToNewContactRtMap.isEmpty())
        {
            Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
            for(Account a : [SELECT Id,(SELECT Id, recordtypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
            {
                existingContactRtMap.put(a.Id,new Set<Id>());
                for(Contact c : a.Contacts)
                    existingContactRtMap.get(a.Id).add(c.RecordTypeId);
            }
            for(Contact c : trgNew)
            {
                if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                {
                    c.addError('There is already a primary contact for this record type.');
                } else {

                    c.Primary__c = true;
                    Account a = new Account();
                    a.Id = c.AccountId;
                    a.Primary_Contact_Email_Address__c  = c.email;
                    newAccountRtMap.put(a.Id,a);


                }
            }
        if(!newAccountRtMap.isEmpty()) {
            update newAccountRtMap.values();
        }

    }
}
public static void onBeforeUpdate(List<Contact> trgNew,Map<Id,Contact> oldMap)
{
    Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
    for(Contact c : trgNew)
    {
        if(String.isNotEmpty(c.AccountId) && c.Primary__c && !oldMap.get(c.Id).Primary__c)
        {
            if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
                accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
            accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
        }
    }
    if(!accountIdToNewContactRtMap.isEmpty())
    {
        Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
        for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
        {
            existingContactRtMap.put(a.Id,new Set<Id>());
            for(Contact c : a.Contacts)
                existingContactRtMap.get(a.Id).add(c.RecordTypeId);
        }
        for(Contact c : trgNew)
        {
            if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
                c.addError('There is already a primary contact for this record type.');
        }
    }
}
}

 
Michael Hedrick 2Michael Hedrick 2
ok. no error.Yes! 
I will test it now and let you know.
Thanks for your patuence and help.
Michael
Michael Hedrick 2Michael Hedrick 2
Bhaswanthnaga - Code is still preventing a secong Primary conact to be added but if there is not a Primary it is not setting the Primary checkbox....
Michael Hedrick 2Michael Hedrick 2
Is this the issue ?  
if(!accountIdToNewContactRtMap.isEmpty())

The list is empty so it is never goes into the If statements correct?
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
I can't help until I see what's happening - nagavivek222@gmail.com
 
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
that's not issue, we have to use if condition