Skip to main content
Ashok Reddy perguntou em #Apex
I have created a picklist field called role in contact object with values manager,lead,developer and created one field called role in account object.

now my requirement is i have 3 contacts to one account with roles manager,lead, developer . I need to write a trigger to update  account role field with manager in this case.

If i have two contacts to account with roles lead and developer at that time i need to update account role with lead.
3 respostas
  1. 18 de mai. de 2022, 03:29
    Hi Ashok,

    Please consider this as the final optmized code as we only need to update account if Role need to update on Account

    trigger 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
0/9000