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
VempallyVempally 

Need Trigger for following Scenario...

Hi Everyone...

In Account sObject we have a field named "Phone"...
While Inserting Account a Contact should get created with the value given in field "Phone"...
When Updating the Account if I change the  Phone Number then a new contact with new phone number should get created...else nothing should happen...

regards,
Suresh
Best Answer chosen by Vempally
Pankaj_GanwaniPankaj_Ganwani
Hi Vempally,

The above mentioned requirement can also be accomplished with the help of Process Builder. For achieving this through code, you can use below mentioned trigger on Account object:
 
trigger AccountTrigger on Account(after update, after insert)
{
	List<Contact> lstContact = new List<Contact>();
	Map<Id,Account> mapOldIdToAccount = new Map<Id, Account>();
	if(Trigger.isAfter)
	{
		if(Trigger.isUpdate)
			mapOldIdToAccount = Trigger.oldMap;
		for(Account objAcc : Trigger.new)
		{
			if(Trigger.isInsert || (Trigger.isUpdate && objAcc.Phone!=mapOldIdToAccount.get(objAcc.Id).Phone))
			{
				lstContact.add(new Contact(LastName = 'Test', Phone = objAcc.Phone));
			}
		}
	}
	
	insert lstContact;
}