top of page

Article 009

Primary Contact Trigger In Salesforce

Things that needs to know are
 

  • One Account may have multiple Contacts

  • One Contact should have only one Account

 

So, One Account may have multiple Contacts then which is the primary Contact for the Account?.

This is the question I asked myself. So what will be the solution?. Yes, Trigger is the right solution for Primary Contact. Because we will place one checkbox on contact object that will ask whether this is primary contact or not if it is primary contact then make it enable otherwise just leave the box as unchecked(disabled).

 

Step 1: Place Check box datatype that says Primary Contact(Primary_Contact__c). Please refer the below image.

 

 

 

 

 

 

 

 

 

Step 2: Write the trigger to perform primary contact for Account whenever the contact is created or updated.

 

So, if one account has already one contact and that contact is primary contact then the user creating another contact for account with enabling the primary contact field then we have to disable(uncheck) the previous contact primary contact field and make newly created record as primary contact if checkbox is enabled while creating.

 

So write a trigger on Contact Object.

 

  trigger PrimaryContact on Contact (before insert, before update) {
  
   
set<id> getid = new set<id>();
    
string contactId;
    
List<Contact> conList = new List<Contact>();
  
    
// Trigger Functionality
    if(Trigger.isInsert || Trigger.isUpdate) {
      
        
for(Contact cont: Trigger.New) {
          
            if(
cont.Primary_Contact__c == true) {
              
                
getid.add(cont.AccountId);
                
contactId = cont.id;
            }
        }
    }
  
   
 // Fetching the other Contact which has primary contact checked
    List<contact> cList = [select id, Primary_Contact__c from contact where accountid IN: getid                                                   AND Primary_Contact__c = true];
  
   
// Unchecking the already checked primary contact
    if(cList.size() > 0) {
      
        
for(Contact newClst: cList) {
          
            if(
newClst.id != contactId) {
              
                
newClst.Primary_Contact__c = false;
                
conList .add(newClst);
            }
        }
    } 
    
update conList
  }



Got the solution?. If not please comment.

bottom of page