Sunday, 26 October 2014

How to write an Apex trigger

Want to get a deeper understanding of our simple apex trigger? Look no further!
Here’s a reminder of the code we wrote in the original post:
trigger ForceForecasting on User (before insert) {
for (User userInLoop : Trigger.new) {
userInLoop.ForecastEnabled = true;
}
}
Let’s take a look at the most important line first. I gave this line a deep green background so you’d know it’s critical!
userInLoop.ForecastEnabled = true;
You can take away nothing else from this post, but just know that this is where all the magic happens. If you wanted to auto-populate the “Company” field on every new user instead, you could change this line to:
userInLoop.CompanyName = 'Google, Inc.';
…while leaving every other line of code the same and it would work!
Let’s move on to the next most important lines of code. This is our loop:
for (User userInLoop : Trigger.new) {
...
}
If this code was translated to normal talk, it would say “For every user in our trigger, do everything inside the brackets { }”. Every Salesforce trigger will always have one of these loops.
Finally, let’s talk about the boilerplate code. You can skip this if you want to save brain power.
trigger ForceForecasting on User (before insert) {
    ...
}
Every trigger in Salesforce has this boring code wrapped around it. All it does is “start” and “end” the trigger.
Glossary of Variables Used
trigger – Every trigger must begin with this!
ForceForecasting – this is the name we gave our trigger. We could’ve named it anything we wanted to!
User – This is the name of the standard sObject in Salesforce. Having this in the first line of code tells our trigger to operate on changes to this object. We can use custom objects too… Salesforce is so awesome!!!
before insert – This tells the trigger to fire before the User is inserted/created. We could’ve saidbefore update if we wanted to as well. See a full list of operations here.
userInLoop – this is the variable we created to represent each specific user in the loop as it iterates one by one across all users in Trigger.new. This variable only exists inside the brackets of the loop! We could’ve made it edit any field on the User object by adding another field API name after the period instead. It’s good manners in the programming world to write variables names in camelCase.
Trigger.new – the special Salesforce variable that is a list of every User captured in our trigger. There will always only be one User unless you’re doing a bulk insert… like through Data Loader!

No comments:

Post a Comment