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
chim chim 9chim chim 9 

Write a trigger on account that assign a primary contact. There can only be one primary contact per account.

When a new Non-Primary Contact is created and the Account related to the new Contact does not have any existing Contacts, the new Contact should automatically become the Account's Primary Contact.

Hi experts. Help me on this one. thank you
Abdul KhatriAbdul Khatri
Hi chim,

Not sure how you are tying Primary Contact to Account i.e. either Lookup or Master Detail. Anyway considering you have custom field on the Account Named PrimaryContact__c, here is the trigger
 
trigger ContactTrigger on Contact (after insert) {
    
    Map<Id, Contact> contactMap = new Map<Id, Contact>();
    for(Contact contact : Trigger.new)
    {
        if(!String.isBlank(contact.AccountId))
        {
            contactMap.put(contact.AccountId, contact);
        }
    }
    
    if(contactMap.isEmpty()) return;
    
    //Get the Account List of only those where Primary Contact is null
    List<Account> accountList = [SELECT Id, PrimaryContact__c FROM Account WHERE Id = :contactMap.keySet() AND PrimaryContact__c = null];
    
    for(Account account: accountList){
        
        account.PrimaryContact__c = contactMap.get(account.Id).Id;
    }
    
    if(!accountList.isEmpty()) update accountList;
        
}

 
Suraj Tripathi 47Suraj Tripathi 47

hi,

Please find the solution.

public class CalculateExpense {
    public static void populateField(List<Contact> newContactList){
        
        List<contact> conList=new List<Contact>();
        List<contact> conListNonPrimary=new List<Contact>();
       
        for(Contact con:newContactList){
            if(con.FullName__c=='Primary' && con.AccountId!=null){
                conList.add(con);
            }else if(con.FullName__c=='Non Primary' && con.AccountId!=null){
                conListNonPrimary.add(con);
            }
        }
        if(conList.size()==0){
            Contact con=new Contact();
            con.Id=conListNonPrimary[0].id;
            con.FullName__c='Primary';
            update con;
        }
    }
}
 
trigger ContactTrigger on Contact (after undelete, before delete,After Insert,After Update,before insert,before update) {
    
    
    
    if(trigger.isAfter && trigger.isInsert){
        set<Id> accountId=new set<Id>();
        for(Contact con:trigger.new){
            accountId.add(con.accountid);
        }
   List<Contact> contactList=new List<Contact>([select id,FullName__c,accountId from Contact where accountid in: accountId]);
       CalculateExpense.populateField(contactList); 
    }
}

Please mark it as the Best Answer if it helps you.

Thank You