November 13, 2021

Trigger to update Account when Contact is Created in Salesforce

Custom Field in Account to update when Contact is created:

Sample Trigger:

trigger ContactTrigger on Contact ( after insert ) {
    
    Set < Id > setAccountIds = new Set < Id >();
    
    for ( Contact objContact : trigger.new ) {
        
        if ( String.isNotBlank( objContact.AccountId ) ) {
            
            setAccountIds.add( objContact.AccountId );
            
        }
    }
    
    if ( setAccountIds.size() > 0 ) {
        
        List < Account > listAccounts = new List < Account >();
        Date dtToday = Date.today();
        
        for ( Id accId : setAccountIds ) {
            
            listAccounts.add( new Account( Id = accId, Last_Contact_Created_Date__c = dtToday ) );   
            
        }
        
        update listAccounts;
        
    }

}

No comments:

Post a Comment