The after event
Then, we can update the after update part on the trigger (some parts of the code have been hidden for simplicity; refer to this book’s GitHub repository for the full code):
1. trigger OpportunityTrigger on Opportunity (before insert, before
2. update, after insert, after update) {
3.
4. //current record (supposing only one opportunity can be saved at
once)
5. Opportunity currentOpp = Trigger.new[0];
6.
7. //treating before and after events separately
8. if(Trigger.isBefore){
9. //. . . hidden for brevity
10. }else if(Trigger.isAfter){
11. if(Trigger.isUpdate || Trigger.isInsert){
12.
13. if(currentOpp.AccountId != null) {
14. //query current account
15. Account acc = [Select Id From Account
16. Where Id = :currentOpp.AccountId];
17. //gets the sum of the amounts of all opportunities
18. //that will be probably colosing this month
19. Double totalAmount = 0;
20. List<Opportunity> oppList = [Select Id, Amount
From Opportunity
21. Where AccountId =
:currentOpp.AccountId
22. and CloseDate = THIS_MONTH
23. and StageName != ‘Closed Lost’];
24. //iterates trhough the opportunity list
25. for(Opportunity opp : oppList){
26. totalAmount += opp.Amount;
27. }
28.
29. //sets the value on the Account object and update it
30. acc.This_Month_All_Deals__c = totalAmount;
31. update acc;
32. }
33. }
34. }
35. }
Whether it is an insert or update operation, we execute a SOQL query on the Account object getting the one that is related to the current opportunity.
Then, we get all opportunities related to the same account that are closing in the current month (we used THIS_MONTH again) and that are not lost. Like the Trigger.new property, the query returns a list of the opportunity type (the triangular brackets state that the list will be of the opportunity type).
With this list, we can iterate through all the elements using a for loop. Element after element, we are summing all the amount fields from the preceding query, thus getting the total amount for all closing deals (this part could have been easily done using the SOQL sum() function).
This cumulative amount is then assigned to the Account. This_Month_All_Deals__c field, and then the account is updated.
This could have been implemented using point and click with the following:
- A formula field on the opportunity object that returns the amount if we are in the current month, or 0 if not.
- A roll-up field on the account object that sums all the formulas of the previous step, getting the total number of closing deals.
Point and click mode may seem easier, but you may have other roll-up fields and formulas on your objects, and you may be close to object limits, so you may be required to write (or make your developers write) a trigger to implement the requirement.
To test it out, try to create some new opportunities. This is the current list of opportunities:
Account’s opportunities list
The current month is September 2019, so this is the total amount on the Account object that is calculated on the trigger any time a new opportunity is updated/created:
Total amount of current month opportunities
Without considering opportunities closed and lost in other months, the total is exactly what the requirement wanted us to implement.
There are some other concepts that a developer should understand and master to write triggers following best practices, such as the concept of bulkification (which is covered extensively in this great Salesforce Developers blog, https://developer.salesforce.com/page/Apex_Code_Best_Practices) to deliver a more robust code, or the better ways to organize the code within a trigger using one of the frameworks out there (have a look at this great video by our trailblazer MVP rockstar Adam Olshansky on the Apex Hours series: https://www.youtube.com/watch?v=U5ZOA9EY3Kg).
The purpose of this section was not to make you the best Apex developer in the world. It is impossible to share all the necessary knowledge without a solid programming background in just one chapter, but I hope you’ve just got a clearer idea of the possibilities that Apex triggers can deliver to your organization.
What else can you do with a trigger that you cannot do with any other automation tool?
- Integrate with an external system (using Apex callouts)
- Manage Apex sharing with complex criteria that cannot be defined using sharing rules
- Handle the update of unrelated objects
- Delete records
If all of this talking about Apex triggers tickled your imagination and you thought why not start on the developer trail?, I suggest you go out your comfort zone of awesome admin and start learning some nerdy Apex stuff from one of the best blogs out there that talks directly to administrators who want to change their careers. SFDC99.com (https://www.sfdc99.com/beginner-tutorials/), built by our MVP David Liu, has a special Apex Tutorial section that’s meant for administrators who want to learn Apex coding, but I also suggest starting with a Trailhead from the following Trailmix, with selected topics dedicated to admins and beginner developers, at https://trailhead.salesforce.com/en/users/enreeco/trailmixes/apex-for-admins.
The code presented here is a simplified version of how a trigger can be implemented, so it may not respect all Apex best practices and coding principles, but it allows a more readable and understandable code. If you plan to start the developer trail and want to master triggers, I challenge you: take the code provided in this example and try to apply the bulkification principle to make it the most performant code ever!