This code is for before insert, before update:
trigger UpdateAccountFields on Account (before insert, before update) {
// Get the set of Account Ids to be updated
Set<Id> accountIds = new Set<Id>();
for (Account acc : Trigger.new) {
if (acc.Industry == 'Banking') {
accountIds.add(acc.Id);
}
}
// Retrieve the related Contacts
Map<Id, Contact> contactsMap = new Map<Id, Contact>(
[SELECT Id, LastName, Phone FROM Contact WHERE AccountId IN :accountIds]
);
// Update the Account fields based on the Contact details
for (Account acc : Trigger.new) {
if (acc.Industry == 'Banking' && contactsMap.containsKey(acc.Id)) {
Contact contact = contactsMap.get(acc.Id);
acc.Name = contact.LastName;
acc.Phone = contact.Phone;
}
}
}
18 respuestas