3 respostas
Hi Ashok,Please consider this as the final optmized code as we only need to update account if Role need to update on Accounttrigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) { List<Contact> contactList = Trigger.isDelete ? Trigger.Old : Trigger.New; Set<Id> accountIdSet = new Set<Id>(); for (Contact con : contactList) { if (Trigger.isUpdate) { if (con.Role__c != Trigger.oldMap.get(con.Id).Role__c || con.AccountId != Trigger.oldMap.get(con.Id).AccountId) { if (con.AccountId != null) accountIdSet.add(con.AccountId); } if (con.AccountId != Trigger.oldMap.get(con.Id).AccountId) { if (Trigger.oldMap.get(con.Id).AccountId != null) accountIdSet.add(Trigger.oldMap.get(con.Id).AccountId); } } else if (con.AccountId != null && String.isNotEmpty(con.Role__c)) { accountIdSet.add(con.AccountId); } } if (accountIdSet.size() > 0) { List<Account> accountList = [SELECT Id, (SELECT Id, Role__c FROM Contacts ORDER BY Role__c LIMIT 1) FROM Account WHERE Id IN :accountIdSet]; if (accountList.size() > 0) { List<Account> accountListToUpdate = new List<Account>(); for (Account acc : accountList) { if (acc.contacts.size() > 0 && acc.Role__c != acc.contacts[0].Role__c) { acc.Role__c = acc.contacts[0].Role__c; accountListToUpdate.add(acc); } else if (String.isNotEmpty(acc.Role__c)){ acc.Role__c = ''; accountListToUpdate.add(acc); } } if (accountListToUpdate.size() > 0) update accountListToUpdate; } } }Please mark this as the best answer if it helps. Thanks
Shubham Jain