+ Start a Discussion
Sonam PatilSonam Patil 

fields values are not updated upon Save in detail page

Hi,
I below trigger and trigger is active,
trigger UpdateAccount on Contact (before insert, before update) {
    Set<ID> accId = new Set<ID>();
    
    for(contact con:Trigger.New){
        accid.add(con.AccountId);
    }
    System.debug('AccID===='+accId);
    Map<ID,Account> accmap = new Map<ID,Account>([Select id, phone from Account where id in:accId]);
    for(contact ct:Trigger.New){
        ct.Phone = accmap.get(ct.AccountId).phone;
    }
    System.debug('accmap===='+accmap);
}
}
But when I am entering the phone value in contact the value is not getting saved in detail page when the trigger is active

User-added image
 
Abhishek BansalAbhishek Bansal
Hi Sonam,

In your trigger you are over-riding the value of the Phone field on your contact record from the Phone field of your related account record. It might be possible that the account which you are selecting on the contact record is having a blank value on the phone field so your trigger is always putting that null value in the phone field of contact record. Please correct/modify your trigger logic. Something like below will work for you :
//Replace the code as mentioned below
for(contact ct : trigger.new){
    if(ct.Phone == null){
        ct.Phone = accmap.get(ct.AccountId).Phone;
    }
}
Please share your requirement, that will make the things more clear.

Thanks,
Abhishek Bansal.
Sonam PatilSonam Patil
Hi,
Still phonr is not getting saved
Thank you
Abhishek BansalAbhishek Bansal

Hi Sonam,

Can you please share the updated code.

Thanks,
Abhishek Bansal.

Sonam PatilSonam Patil
Hi Abhishek,
Below is my Updated Code, Please check and let me know how to overcome this issue.

trigger UpdateAccount on Contact (before insert, before update) {

    Set<Id> accIds = new Set<Id>();
    for(Contact con : trigger.new)
    {
        accIds.add(con.AccountId);
    }
     System.debug('AccID===='+accIds);
    
    Map<Id,Account> accountMap = new Map<Id,Account>( [select Phone from Account where id in: accIds] );
    for(Contact con : trigger.new)
    {
        con.phone = accountMap.get(con.accountId).Phone;
    }
      System.debug('accmap===='+accountMap);
}
}

Thanks,
Sonam
Abhishek BansalAbhishek Bansal
Hi Sonam,

Please use the below updated code:
trigger UpdateAccount on Contact (before insert, before update) {

    Set<Id> accIds = new Set<Id>();
    for(Contact con : trigger.new)
    {
        accIds.add(con.AccountId);
    }
     System.debug('AccID===='+accIds);
    
    Map<Id,Account> accountMap = new Map<Id,Account>( [select Phone from Account where id in: accIds] );
    for(Contact con : trigger.new)
    {
        if(con.Phone == null){
            con.phone = accountMap.get(con.accountId).Phone;
        }
    }
      System.debug('accmap===='+accountMap);
}
}

Let me know if you need any further help.

Thanks,
Abhishek Bansal