You need to sign in to do that
Don't have an account?
Trigger to increment/decrement field on related object
I received some helpful feedback here to write a trigger on opportunity to update a field on a related contact, linked through a lookup field. I now understand how to do a simple field update on a picklist field on a related object.
I now need to write a revised version to actually increment or decrement a counter field (Active_Count__c) on the related contact. If Opp Stage = Active, Active_Count__c needs to be the previous value + 1. If Opp Stage is not Active, Active_Count__c needs to be the previous value -1. I'm not sure how to express the previous value or the addition/subtraction. I have question marks at those places in the code.
Here is what I have so far:
trigger OpportunityRelatedContact2 on Opportunity (after insert, after update) { { Map<Id,Id> instructorsToOppsMap = new Map<Id,Id>(); for(Opportunity A : trigger.new) instructorsToOppsMap.put(A.InstructorName__c,A.Id); List<Contact> contactsToUpdate = new List<Contact>{}; for (Contact Instructor: [SELECT Id,Active_Count__c FROM Contact WHERE Id IN: instructorsToOppsMap.keySet()]) { Id oppId = instructorsToOppsMap.get(Instructor.Id); Opportunity opp = trigger.newMap.get(oppId); if (opp.StageName=='Active'){ Instructor.Active_Count__c= ???Active Count value + 1 ; }else { Instructor.Active_Count__c= ???Active Count value - 1; contactsToUpdate.add(instructor); } } if(contactsToUpdate != null && !contactsToUpdate.isEmpty()) Database.update(contactsToUpdate); } }
Thanks for the input!
I copy-pasted that as is ! Changed now
All Answers
That's helpful; thank you.
I'm getting:
Error: Compile Error: expecting a semi-colon, found 'value' at line 15 column 66
Is there some other way to write "Instructor.Active Count value + 1 ;"?
I copy-pasted that as is ! Changed now
OK, thanks. I think this works, provided I have a default value of 0 for the Active Count field.