You need to sign in to do that
Don't have an account?
Help getting my trigger to work
Hi all!
I'm still pretty new to writing apex triggers but I got this one to (kind of) work in my sandbox. The trigger does part of what I need it to, but not all of what I need it to. Here is what I'm trying to do:
The Contact record has a checkbox on it called Primary Contact (Primary_Contact__c) and the Account record has a lookup field on it called Primary Contact (also called Primary_Contact__c). When the box is checked on the Contact it should populate the lookup field with that Contacts name. So far I have that part working! What I cannot get to work is if the Contact checkbox becomes unchecked and having that remove the Contact name from the Primary Contact lookup field on the Account.
Thanks in advance for any assistance. Any help on the test class would be greatly appreciated too!! Here is my trigger:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | trigger UpdateAccount on Contact (after update) { Map<Id, Contact> contactsToCheck = new Map<Id, Contact>(); for (Contact newCon : Trigger.New) { Contact oldCon = trigger.oldMap.get(newCon.Id); if (newCon.Primary_Contact__c != oldCon.Primary_Contact__c) { contactsToCheck.put(newCon.AccountId,newCon); } } List<Account> accs= [select id,Primary_Contact__c from Account where id IN: contactsToCheck.keySet()]; for(Contact c : Trigger.new){ if(c.Primary_Contact__c==TRUE ){ for(Account acc : accs){ acc.Primary_Contact__c = c.id; } } } update accs; } |
try this
All Answers
try this.
Thank you for the help Naidu but unfortunately it didn't work. When I uncheck the Primary Contact checkbox on the Contact the name still remains in the lookup on the Account.
try this
Thanks Naidu - it works perfectly now!