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
RRKRRK 

Primary Contact on Account

Hi can someone help me in writing a trigger for the below scenario as i'm new for coding and do not have much  experience in writing trigers

When a Contact is updated and Primary checkbox is set, that contact will become the primary contact and the reference should get updated on Parent Account. The Primary Contact flag should be true for only one contact at a time. If an Account has no Contacts, then the first created contact by default becomes the primary and that value should be set in reference. If the primary contact is deleted, the next available contact, if there is any, should be the primary contact and the relationship on account should reflect this. If all contacts are deleted, the primary contact reference on Account will be Blanked out. Test Class as well for it.
logontokartiklogontokartik
Please check the below code, maybe this will help
 
trigger primaryContact on Contact (after insert, after update) {
      Set<Id> accountIds = new Set<Id>();
      List<Account> updatedAccounts = new List<Account>();
      for (Contact c : Trigger.new) {
        accountIds.add(c.AccountId);
      }
      // Get accounts with their contacts.
      Map<Id,Account> accountMap = new Map<Id,Account>([Select Id, Primary_Contact__c, (Select Id, Name from Contacts where IsPrimary__c = true) from Account where Id in :accountIds]);
      // Iterate over the new data from trigger
      for (Contact c : Trigger.new) {
        if (c.IsPrimary && accountMap.get(c.AccountId)) {
            Account updAccount = accountMap.get(c.AccountId);
            updAccount.Primary_Contact__c = c.Id;
            if (updAccount.Contacts != null && updAccount.Contacts.size()>0) { // This will identify if account already has primary contact set
              // Not sure what you want to do? Throw an error? or turn off the iS Primary on older contact?
            }
            
            updatedAccounts.add(updAccount);
        } 
      }
      
      update updatedAccounts;
}

 
Santhosh Gaddam 3Santhosh Gaddam 3
it is possible to do in workflow?
 
Cong NguyenManhCong NguyenManh
Dir Santhosh Gaddam 3!!!
Because need contact Id for update on Account. so, workflow cannot do that