+ Start a Discussion
Salesforce seekarSalesforce seekar 

Trigger --> please correct the below code ... value is not populating

we have a custom  checkbox on contact  is_primary__c , if we enter a number in field "  phone " on contact , corresponding Account should also have the same number populated on account . 



solution :

//Phone number from primary Contact (if Is_Primary__c checkbox is true )  will get updated to parent Account
//verified and working fine
trigger IsprimaryCOntact on Contact (after insert , after update ) 
{
  // contacts will be having id,accountid , so adding to their respective id 
Set<Id> accountIdSet= new Set<Id>();
Set<Id> contactIdSet=new Set<Id>();
List<Account> updateAccList=new List<Account>();
        
            for(Contact contact:Trigger.new)
            {
                accountIdSet.add(contact.accountId);
                contactIdSet.add(contact.Id);
            }
            // Get accounts with their contacts.
 Map<Id,Account> accountMap=new Map<Id,Account>([select id, Phone,(select id, Name from Contacts where Is_Primary__c=true and 
                                                               id not in :contactIdSet) from Account where Id in: accountIdSet]); 
 
 
                                                                          
   
   // checking the data     
           
            for(Contact contact:Trigger.new)
            {
            
                if(contact.Is_Primary__c && accountMap.containsKey(contact.accountId))
                {
                    //This will identify if account already has primary contact set
                    Account updAccount = accountMap.get(contact.accountId);
                    system.debug('--updAccount--'+updAccount);
                    updAccount.Phone=contact.Phone;
                    
                        if(updAccount.Contacts!= null && updAccount.Contacts.size() >0)
                        {
                            contact.addError('Error in saving data!!! Account already has primary contact');                                                
                        }
                    updateAccList.add(updAccount);
                }
            }
            
        update updateAccList;
}  
 
santanu boralsantanu boral
What type of issue you are facing? Code seems to be okay.
Salesforce seekarSalesforce seekar
@santanu ... hi , can you please copy the code and check it in your org please , for the phone value for account is not population , sometimes it is taking more time 
 
santanu boralsantanu boral
I have checked it at my org, it is working fine.