Writing your first APEX trigger (with a test class as well!)

If you are new to programming on the awesome Salesforce platform, you might have come across the need to write Triggers.

Initially, most folks have trouble understanding how triggers work. So why don’t we write a simple APEX trigger and see how triggers work in Salesforce.

A trigger is basically a piece of code that executes before or after certain operations are performed in Salesforce.

For now lets focus on two operations, namely Insert and Update.

Lets keep this trigger simple. There are other ways of doing this but lets assume that when you create or Edit a new account, if the Industry field is blank, then it should be defaulted to a certain value which is “Not For Profit”.

This can be written easily like this:

trigger setDefaultIndustry on Account (before insert, before update)
{
    for (Account accountObj : trigger.new)
    {
        accountObj.Industry = 'Not For Profit';
    }
 
} 

First lets analyze this syntax. The trigger keyword denotes that this is a trigger. The object name is specified after “on”. Then we are specifying that this trigger will execute both on the insert and update operations. Note that we are using the “before” keyword. For now you should know that we can have before and after triggers. You will probably use before triggers for the most part. Before triggers are triggers that are executed before your record is committed to the database. This means that you should use before triggers to do things like validations, set default values etc.

Note that you cannot use the record id in a before trigger as the record has not been inserted into the database yet. If you need the current record id, then you would use an After trigger.

Now coming back to our trigger – though this trigger will work and do the job, it is a good practice to learn to write triggers that do not contain logic and instead invoke “Handler classes” which do the heavy lifting.

So what this means is that this trigger would now invoke an APEX class which will perform the actual work that needs to be done. Later you will learn that by doing this you can make your code more maintainable and it will easy to make changes going forward.

So lets create a handler class:

public class AccountTriggerHandler
{
    	public static void handleBeforeInsert(List<Account> accountList)
    	{
                for (Account accountObj : accountList)
	        {
	            accountObj.Industry = 'Not For Profit';
	        }
	}
 
        public static void handleBeforeUpdate(List<Account> accountList)
	{
	    for (Account accountObj : accountList)
	    {
	    	if (accountObj.Industry == null)
	    	{
	        	accountObj.Industry = 'Not For Profit';
	       	}
	    }
	}
}

Now our original trigger needs to be modified to invoke this handler class.

trigger AccountTrigger on Account (before insert, before update)
{
    for (Account accountObj : trigger.new)
    {
       if(Trigger.isBefore && (Trigger.isInsert) )
       {
       		AccountTriggerHandler.handleBeforeInsert(Trigger.new);
 
       }
 
       if(Trigger.isBefore && (Trigger.isUpdate) )
       {
       		AccountTriggerHandler.handleBeforeUpdate(Trigger.new);
 
       }
    }
 
} 

Now our trigger is simply invoking the appropriate method based on whether it is an insert or update operation.
Note that we are using certain variables such as “Trigger.new” . These are called context variables and are provided by Salesforce to make our lives easier.

Read more about them below.

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables.htm

Now our trigger is complete. The next step is to write a test class for this trigger. Ideally a test class should provide 100% code coverage and also test the functionality of the trigger.

But let us write a simple test class for now. To test this trigger, all you would need to do is to insert and update an account record.

@isTest 
private class AccountTriggerTest {
    static testMethod void validateAccountTrigger() {
      Account acc = new Account(Name='Test Acc 1');
 
 
       // Insert account
       insert acc;
 
       // Retrieve the new account
       acc = [SELECT Id,Industry FROM Account WHERE Id =:acc.Id];
 
 
       // Test that the trigger correctly updated the industry
       System.assertEquals('Not For Profit', acc.Industry);
 
       update acc;
       // Test that the trigger correctly updated the industry
       System.assertEquals('Not For Profit', acc.Industry);
    }
}

So there it is. An APEX trigger and a test class for it. Please do let me know if you have any questions or needed help with triggers.

This was a very basic implementation. As you learn more about triggers, you will realize that APEX triggers can be very powerful when you implement them with certain proven design patterns. I will explore more in a future post.