I want to write a trigger on Contact-when contact is created and if primary checkbox is true update parent account phone with contact phone. I am new to coding Here is my code...

trigger PrimaryContactValidation on Contact (before update,before insert) {
    set<id> accountids=new set<id>();
    for(contact con:trigger.new){
    map<id,account> mapacc=new map<id,account>([select id,(select accountid from contacts) from account where id in :accountids]);
    list<string>acclist=new list<string>();
    for(contact acc:trigger.new){


    for(account ac:acclist){


I am not able to write exact trigger.

3 Answers 3


The basic logic would be something like this. I haven't test it so there might be some syntax issues.

 trigger PrimaryContactValidation on Contact (before insert)

 Map<id,String> accountmap =new Map<Id,String>

 for(contact con:trigger.new){ 
   if(con.is_primary__c==true && con.phone!=null) {
       accountmap.put(c.accountid, c.phone);

    List<Account> accountsToUpdate = new List<Account>([Select id, phone from account where id in: accountmap.keyset()]);

     for(Account a: accountsToUpdate){

    update accountsToUpdate;


Usually I refrain from answering "write me my implementation" questions like this, but seeing as this one has an accepted answer which is far from optimal (probably by mistake, but still)... You should use this;

trigger PrimaryContactValidation on Contact (before insert, before update) {
    Account[] acctsToUpdate = new Account[]{};
    for(Contact con : Trigger.new) {
        if(con.Is_Primary__c && !String.isBlank(con.Phone)) {
            Account a = new Account();
            a.Id = con.AccountId;
            a.Phone = con.Phone;

Note that this can be enhanced to make sure no account has more than one primary contact etc, but this is the main logic you should use.


Just use Process Builder. There is no readily apparent reason you need to use a trigger for this functionality.

  1. Navigate to Create > Workflows & Approvals > Process Builder.

  2. Click New.
    Fill in Process Name > Contact Account Sync.
    No need to fill in API Name, it will auto-populate.
    You may fill in an optional Description.
    Click Save.

  3. Click + Add Object.
    Select Contact.
    Choose Start the process > when a record is created or edited.
    Click Save.

  4. Click + Add Criteria.
    Fill in Criteria Name > My Checkbox Checked
    Select Conditions are met.
    Select Field > My Checkbox.
    Select Value > True.

  5. Click + Add Action.
    Select Action Type > Update Records.
    Fill in Action Name > Update Account Phone.
    Choose Select a record related to the Account.
    Select Record Type > Account ID.
    Select Field > Account Phone.
    Select Type > Reference.
    Select Value > Contact Phone.
    Click Save.

  6. Click Activate.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .