function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ashish jadhav 9ashish jadhav 9 

how to write trigger to change contact phone number when account phone number change?

Hey guys I'm new to salesforce and I've to update all phone numbers on contact when account phone number changes, how can I do this with trigger? please help.
Best Answer chosen by ashish jadhav 9
sharathchandra thukkanisharathchandra thukkani
Process looks like this

All Answers

Vasani ParthVasani Parth
Ashish,

Try this,
trigger phupdate on Contact (after insert,after update) {
	List<account> li=new list<Account>();
	List<Id> ids = new List<Id>();
	for(Contact c: trigger.new)
		ids.add(c.AccountId);
	Map<Id, Account> accountMap = new Map<Id, Account>([Select Id, Phone From Account Where Id In :ids]);
	for(Contact c: trigger.new)
	{
		Account a = accountMap.get(c.AccountId);
		if(a != null)
		{
			a.Phone= c.MobilePhone;
			li.add(a);
		}
	}
	update li;
}
Please mark this as the best answer if this helps
 
sharathchandra thukkanisharathchandra thukkani
No need of trigger to achieve this you can do this by process builder. No coding is required.

go through below link for more information on process builder overview.

https://help.salesforce.com/HTViewHelpDoc?id=process_overview.htm

 
sharathchandra thukkanisharathchandra thukkani
Process looks like this
This was selected as the best answer
Dhriti Moulick 16Dhriti Moulick 16
Please use the following code:

trigger AccountTrigger on Account (After Update) {
    AccountTriggerHandler accountHandler = new AccountTriggerHandler();
    if(Trigger.isUpdate && Trigger.isAfter){
       accountHandler.onAfterUpdate(Trigger.newMap,Trigger.oldMap);
    }
}


Handler class is as follows:

public Class AccountTriggerHandler{
      public AccountTriggerHandler(){
      }
      
      public void onAfterUpdate(Map<Id,Account> newMapAccount,Map<Id,Account> oldMapAccount){
           List<Account> fetchAccountList = new List<Account>();
           
           for(Id accMap:newMapAccount.keyset()){
               if(newMapAccount.get(accMap).Phone <> oldMapAccount.get(accMap).phone){
                  fetchAccountList.add(newMapAccount.get(accMap));
               }
           }
           Map<ID,Account> fetchAccContacttList = new Map<Id,Account>([Select Id,Phone,(Select Id,Phone from Contacts) from Account where Id in:fetchAccountList]);
           Map<Id,List<Contact>> fetchContacts = new Map<Id,List<Contact>>();
           for(Account acclIst:fetchAccContacttList.values() ){
               if(!accList.contacts.isEmpty()){
                  fetchContacts.put(acclIst.Id,acclIst.contacts);
               }
           }
           List<Contact> contactUpdate = new List<Contact>();
           for(Id cseId:fetchContacts.keyset()){
               List<Contact> contactsList = new List<Contact>();
               contactsList = fetchContacts.get(cseId);
               for(Contact cnts:contactsList){
                 
                   Account acc= fetchAccContacttList.get(cseId);
                   
                   cnts.phone = acc.Phone;
                   contactUpdate.add(cnts);
               }
           }
           
           update contactUpdate;
     }
}


Cheers,
Dhriti
JyothsnaJyothsna (Salesforce Developers) 
Hi,

Please try this below code
 
trigger Crossobjectfieldupdate on Account (after update) {
List<Contact> con=new List<Contact>();
Account acc;
Contact cc;
List<Contact> Updatecon=new List<Contact>();
if (Trigger.isUpdate)
{
    acc=Trigger.New[0];
    con=[select id, phone from contact where accountid=:acc.id];
    if(con.size()>0)
        for(contact c:con)
        {
            cc=new Contact(id=c.id,phone=acc.phone);
            Updatecon.add(cc);
        }
}
 
update Updatecon;
 
}

Hope this helps you!

Best Regards,
Jyothsna
Amit Chaudhary 8Amit Chaudhary 8
Hi ashish jadhav 9,

Always consider below point while writing trigger
1) Try to avoid hard code index, Trigger should be bulky
2) Never use SOQL inside for loop.

Please try below code
trigger AccountTrigger on Account (after update) 
{

	Set<ID> setAccId = new Set<ID>();
	for(Account acc : Trigger.new)
	{
		Account oldAcc = trigger.oldMap(acc.id);
		if( acc.phone != oldAcc.phone )
		{
			setAccId.add(acc.id);
		}
	}
	if(setAccId.size() > 0 )
	{
		Map<Id,Account> mapAccount = Map<Id,Account> ([select id,phone (select id,phone from contacts ) from account where id in :setAccId ]);
		List<Contact> lstContactToUpdate = new List<Contact>();
		
		for(Account acc : Trigger.new)
		{
			Account oldAcc = trigger.oldMap(acc.id);
			if( acc.phone != oldAcc.phone )
			{
				if(mapAccount.containsKey(acc.id))
				{
					Account accObj = mapAccount.get(acc.id);
					List<Contact> lstCont = accObj.contacts;
					for(Contact cont : lstCont)
					{
						cont.phone = acc.phone;
						lstContactToUpdate.add(cont);
					}
				}
			}
		}
		
		if(lstContactToUpdate.size() > 0 )
		{
			update lstContactToUpdate;
		}
	}
}
Please check below post trigger framework
1) http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html


Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org. 

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail

Please let us know if this will help you
 
ashish jadhav 9ashish jadhav 9
Thanks sharathchandra thukkani, can you please let me know how to do that as the screenshot is not clear, what else we can do with process builder, I mean insted of trigger with simple configuration what else we can do? please guide.
ashish jadhav 9ashish jadhav 9
Hi Amit, I noticed that you're always part of solution :) 

And as usual I'm wondering here with too many question about salesforce ;)  I need your help, please refer below link.
https://developer.salesforce.com/page/Checkbox_in_DataTable?language=en

I've to display list of account with checkbox on vf page and 1 button called submit. so for ex. we've 10 records in account in which I select any 3 when I select the records and click on submit then selected records should be on right side column i.e. 3 records and remaining records on left side of the page.

Can you please help me in this scenario?
ashish jadhav 9ashish jadhav 9
yeah but didn't get any solution :( 
niranjan gaddam 6niranjan gaddam 6
trigger Updatephone on Account (after insert,after update) {
      set<id> Accounidq = new set<id>();
    list<contact> contoUpdate=new list<contact>();
    for(Account acc:trigger.new)
    {
       // Account oldphone = trigger.oldmap.get(acc.Id);
        if(acc.phone!= trigger.oldmap.get(acc.Id).phone){
            Accounidq.add(acc.id);
        }
    }
    for(contact con :[select id,Phone,Account.phone from contact where Accountid in:Accounidq]){
        for(Account acc:trigger.new){
            if(con.AccountId==acc.id){
            con.Phone=acc.phone;
                contoUpdate.add(con);
            }
        }
            
        
    }
    update contoUpdate;
}
    
    
smriti sharan19smriti sharan19
trigger UpdatephoneTrigger on Account (after update) {
      set<id> AccounidSet = new set<id>();
    list<contact> contoUpdate=new list<contact>();
    for(Account acc:trigger.new)
    {
       // Account oldphone = trigger.oldmap.get(acc.Id);
        if(acc.phone!= trigger.oldmap.get(acc.Id).phone){
            AccounidSet .add(acc.id);
        }
    }
    for(contact con :[select id,Phone,Account.phone from contact where Accountid IN: AccounidSet ]){
        for(Account acc:trigger.new){
            if(con.AccountId==acc.id){
            con.Phone=acc.phone;
                contoUpdate.add(con);
            }
        }
    }
    update contoUpdate;
}
Raghu 720 : AdminRaghu 720 : Admin
Thanks
Shaswat Sinha 14Shaswat Sinha 14
Here is a simple bulky trigger:
 

    set<ID> AccountIDset= new set<ID>(); //all account id in trigger.new

    List<Contact> conListToBeUpdated= new List<Contact>();

    
for(Account a: trigger.new)

    {

        AccountIDset.add(a.Id);

    }

    

    if(AccountIDset.size()>0){

    for(Account acc: trigger.new)

    {

        for(contact con:[select id,name from contact where accountid in :AccountIDset])

        {

             con.Phone=acc.Phone;

            conListToBeUpdated.add(con);

        }

    }

    }

    update conListToBeUpdated;

    

}


 
JAYA SIVANKUTHALINGAMJAYA SIVANKUTHALINGAM
Update contact phone when account phone is updated, write trigger on account after update context....
Some best practices to follow. 
      1. Avoid using SOQL inside for loop
      2. Use SOQL for loop to avoid heap size limit.
      3. Bulkify your code & use Trigger Handlers
      4. Avoid using for loop inside for loop.

     List<Id>  accId = new List<Id>();   // we can use set also, since record Id will not have any duplicate I am using list here. 
     List<contact> contactToUpdate = new List<contact>();

for(account acc : Trigger.new){
    if(acc.phone != Trigger.oldMap.get(acc.Id).phone)   //checking whether phone value is changed or not. 
   {
      accId.add(acc.Id);
    }
}

if(accId.size>0){
    for(contact con :  [select id, name, accountId, account.phone from contact where accountId in :accId]){
     con.phone = con.account.phone;
     contactToUpdate.add(con);
     }
}

if(contactToUpdate.size()>0){
   update contactToUpdate;
}
 
bhupal reddy 7bhupal reddy 7
trigger UpdateAccountPhonewhenContactIsUpdated on Contact (After Update) {
    List<Account> AcclistToUpdate = new List<Account>();
    Map<Id,Contact> MapOfContact = new Map<Id,Contact>();
    For(contact Con : Trigger.new){
        If(Con.AccountId != Null){
            MapOfContact.Put(Con.AccountId,Con);
        }
    }
    List<Account> AccList = [Select id, Name,Phone From Account where Id =:MapOfContact.keyset()];
    For(Account Acc:AccList){
        Account Acc1 = New Account();
        If(MapOfContact.containsKey(Acc.Id)){
            Acc1.Id =Acc.id;
            Acc1.phone=MapOfContact.get(Acc.id).phone;
            AcclistToUpdate.Add(Acc1);
        }
        If(!AcclistToUpdate.Isempty()){
            Update AcclistToUpdate;
        }
    }
}

Please find this if any query, feel free to revert.
Thank you,
Bhupal Reddy.
Divan MydeenDivan Mydeen
Try this below code:::::

trigger AccountnewTrigger on Account (after update) {
    
    Switch On Trigger.OperationType{
        WHEN AFTER_UPDATE{
            List<Contact> conlist = [Select Id, Name, Phone, AccountId From Contact Where AccountId=: Trigger.New];
            for(Contact conrecord:conlist){
                conrecord.phone=Trigger.NewMap.get(conrecord.AccountId).phone;
            }
            update conlist;
        }
      
 }
}

Thanks Divan
Oindry Sen 10Oindry Sen 10
trigger AccContPhoneFUpdate on Account (after update) {
    set<Id> accntId = new set <Id>(); 
    list<contact> conlist = new list<contact>();
    for(Account acc : Trigger.new)
    {
      if(trigger.oldMap.get(acc.Id).Phone != acc.Phone)
      {
          accntId.add(acc.Id);     
      }
        if(accntId.size() > 0)
        {
               for(Contact con : [select id,Name ,Phone from contact where AccountId in : accntId ])
                {
                    con.Phone = acc.Phone;
                  conlist.add(con);
                }
            
        }  
    }
    update conlist;
}