You need to sign in to do that
Don't have an account?

Hi guys, I want to write a trigger on account to update contact fields.
Actually the condition is that i have department field picklist in Account, whenever i change the department(picklist) from account it should be reflect to the department field in contact. I have to write a trigger to update the records in contact.
<pre>
// figure out which accounts have changed department
Set<Id> accountIdsWithNewDepartment = new Set<Id>();
for ( Account account : Trigger.new )
{
Account oldAccount = Trigger.oldMap.get( account.Id );
if ( newAccount.Department__c != oldAccount.Department__c )
{
accountIdsWithNewDepartment.add( account.Id );
}
}
// update the contacts on the affected accounts
if ( !accountIdsWithNewDepartment.isEmpty() )
{
List<Contact> contactsToUpdate =
[ SELECT Id, Department__c, AccountId
FROM Contact
WHERE AccountId IN :accountIdsWithNewDepartment
];
for ( Contact contact : contactsToUpdate )
{
contact.Department__c = Trigger.newMap().get( AccountId ).Department__c
}
update contactsToUpdate;
}
</pre>
All Answers
Trigger on Account to update Contact may I suggest you please refer the below link for reference.
- https://stackoverflow.com/questions/43375534/trigger-on-account-to-update-contact
- https://developer.salesforce.com/forums/?id=906F0000000B1cbIAC
Hope it will be helpful.Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.
Thanks
Rahul Kumar
Correct the Department__c field api name in the below code.
public static void populateDepOnContact(List<Account> vLstAccount)
{
List<Contact> vLstContact = [Select Id, AccountId, Department__c from Contact where AccountId In: vLstAccount];
for(Account vAccount: vLstAccount)
{
for(Contact vContact: vLstContact)
{
if(vAccount.Id == vContact.AccountId)
{
vContact.Department__c = vAccount.Department__c;
}
}
}
if(!vLstContact.isEmpty())
{
update vLstContact;
}
}
<pre>
// figure out which accounts have changed department
Set<Id> accountIdsWithNewDepartment = new Set<Id>();
for ( Account account : Trigger.new )
{
Account oldAccount = Trigger.oldMap.get( account.Id );
if ( newAccount.Department__c != oldAccount.Department__c )
{
accountIdsWithNewDepartment.add( account.Id );
}
}
// update the contacts on the affected accounts
if ( !accountIdsWithNewDepartment.isEmpty() )
{
List<Contact> contactsToUpdate =
[ SELECT Id, Department__c, AccountId
FROM Contact
WHERE AccountId IN :accountIdsWithNewDepartment
];
for ( Contact contact : contactsToUpdate )
{
contact.Department__c = Trigger.newMap().get( AccountId ).Department__c
}
update contactsToUpdate;
}
</pre>
<pre>
contact.Department__c = Trigger.newMap().get( contact.AccountId ).Department__c
</pre>