You need to sign in to do that
Don't have an account?
Josh Schwerdtfeger
automatically running triggers
Need some help, i'm in over my head. I've got a custom field on a custom object and have the following apex running on a trigger. I don't know how or what would be the best way to execute this field update automatically. On one hand it would be great to exeute the trigger every night at midnight, as i will be duplicatingt he field and query for each month. Any help or a point in the right direction would be great.
trigger WonNov on Course__c (before update) { Set<Id> setRecordId = new Set<Id>(); for (Course__c obj : Trigger.new) { setRecordId.add(obj.id) ; } AggregateResult[] groupedResults = [ Select SUM (Amount) sum, Course_Lookup__c from Opportunity WHERE Courseid__c in :setRecordId AND Opportunity_Type__c ='Outing' AND Probability >94.00 AND Event_Date__c = THIS_YEAR AND Event_Month__c = '11_November' GROUP BY Course_Lookup__c ]; Map<String , AggregateResult > mapAG = new Map<String , AggregateResult >(); for(AggregateResult ar : groupedResults) { mapAG.put(String.valueOf(ar.get('Course_Lookup__c')) , ar ); } for (Course__c obj : Trigger.new) { if( mapAG.containsKey(obj.id) ) { AggregateResult ar = mapAG.get(obj.id); double sum =double.valueOf(ar.get('sum')); obj.Won_Nov_Outings__c = decimal.valueOf(sum); } } }
You can achieve what you want by doing the following steps.
- Create a trigger service class and move the code logic to that class.
- call the newly created class from the trigger by passing the records as a parameter.
- Now, create a batch class that queries all the required records to be processed every night.
- From the batch class, call the newly created trigger service class by passing the records.
- Schedule the Batch class at the time you want.
This way, logic is executed when some one manually updates, and also at the scheduled time.Mark this answer as best answer if this solves your question.
Thanks,
Vishnu
Thank you for this outline, i'll give this a try. Question, would another way to solve this be possible where the trigger is when an opportunity is updated, but the field that is updated is on a child object? This would make the field update as opportunities update instead of every night. Woudl this be much harder to do?
It will only be fired when an opportunity is updated.