+ Start a Discussion
sourav046sourav046 

Apex code for Contact to Account Update

I want to create a trigger on Contact so that when I update the Phone No in Contact ,the associated Account also gets populated with that Phone No.

 

Help with code Please .

Best Answer chosen by Admin (Salesforce Developers) 
sourav046sourav046

Thanks SLockard !

 

Your code helped me alot .

But I did this :

trigger contact_ph_change on Contact(before update){

Map<Id,String> mapcon=new Map<id,String>();
   for(Contact c:trigger.new)
   {
     mapcon.put(c.AccountId,c.phone);
   }
List<Account> acc=new List<Account>();
   for(Account a:[select phone,id from Account where id IN:mapcon.keyset()])
   {
    a.phone=mapcon.get(a.id);
    acc.add(a);
    update a;
   }
}

 

All Answers

SLockardSLockard

Try something like this:

trigger updatePhoneNumber on Contact(after update)
{
	Map<Id, Contact> contactsToCheck = new Map<Id, Contact>();
	for (Contact newCon : Trigger.New)
	{
		Contact oldCon = trigger.oldMap.get(newCon.Id);
		if (newCon.PhoneNumber != oldCon.PhoneNumber)
		{
			contactsToCheck.put(newCon.AccountId, newCon);
		}
	}
	
	if (contactsToCheck.size() > 0)
	{
		List<Account> accsToUpdate = [SELECT Id, PhoneNumber FROM Account WHERE Id IN :contactsToCheck.keySet()];
		for (Account acc : accsToUpdate)
		{
			acc.PhoneNumber = contactsToCheck.get(acc.Id).PhoneNumber;
		}
		if (!accsToUpdate.isEmpty())
		{
			update accsToUpdate;
		}
	}
}

 Hope that helps!

sourav046sourav046

Thanks SLockard !

 

Your code helped me alot .

But I did this :

trigger contact_ph_change on Contact(before update){

Map<Id,String> mapcon=new Map<id,String>();
   for(Contact c:trigger.new)
   {
     mapcon.put(c.AccountId,c.phone);
   }
List<Account> acc=new List<Account>();
   for(Account a:[select phone,id from Account where id IN:mapcon.keyset()])
   {
    a.phone=mapcon.get(a.id);
    acc.add(a);
    update a;
   }
}

 

This was selected as the best answer
SLockardSLockard

The only issue I see with your code is that you are updating each account separately. The reason I used the list to hold the accounts and update them together is because of governor limits..

sourav046sourav046

I tried to update bulk records using data loader .It works fine .

 

Is it the issue you found here ?


SLockardSLockard

If it's working for you, great. But usually it is not a good idea to put an update in a for loop.

Either way, I'm glad I could help.

sourav046sourav046

Hi SLockard  !

 

You can share your idea anytime .Afterall i am almost a newbie to apex coding and I want to improve myself .


I would be glad to see your code .