SalesforceTrending News

Apex Triggers

Apex triggers enable you to perform custom actions before or after events to records in Salesforce, such as insertions, updates, or deletions. Typically, you use triggers to perform operations based on specific conditions, modify related records, or restrict certain operations from happening. Use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface.

Trigger Syntax

In the below code, we created a trigger called Hellworld on the Account object. We want that trigger to run when a new account is created. That was why we have written before insert inside the brackets.

trigger Helloworld on Account (before insert) {
    System.debug('I am a trigger');
}

We need to test it now. We can create an account and see if we are going to receive I am a trigger message or not.

//We just excute our code anonymously.

Account a = new Account(Name='Test Trigger2');
insert a;
We receive our message when our account has been created.

Using Context Variables

To access the records that caused the trigger to fire, use context variables. For example, Trigger.New contains all the records that were inserted in insert or update triggers. Trigger.Old provides the old version of sObjects before they were updated in update triggers, or a list of deleted sObjects in delete triggers.

This time we will use a trigger to update a field in the Account object whenever a new account is created.

Here is our code.

trigger Helloworld on Account (before insert) {
    for(Account a : Trigger.New){
        a.description ='I am new here';
        a.Active__c = 'yes';
    }
}

The helloworld trigger works only whenever a new account is created. We use for loop to check the instance of newly created accounts with Trigger.New. Inside the for loop, we are basically asking our trigger to update the description and status of the newly created account.

When we test if our trigger will fire or not.

Account a = new Account(Name='Test Trigger3');
insert a;

Result is;