How to get the ID of the account that fired a trigger in Salesforce Apex

Published May 3rd 2018

So I'm working on a project in work where I need to be able to pass information between a couple of systems via various APIs. One of those APIs belongs to Salesforce.

Basically, the situation I found myself in was needing to be able to identify the ID of the account that fired a trigger within Salesforce. I originally looked into using a SOQL query to identify the ID, but it wasn't reliable and sometimes returned the wrong account.

After a bit of digging through the documentation and playing around with some of the more basic examples, I remembered about limiting the scope of a trigger using Trigger.new.

To cut a very long story short, the code that allows you to pull out the ID of the account the fired the trigger is this:

trigger AccountActivation on Account (after insert)
{
    for (Account a : Trigger.new)
    {
        system.debug(a.id);
    }
}

In this case, I'm assigning the account sObject that fired the trigger to the variable a. I'm then accessing the id of the sObject to retrieve the Salesforce ID of that account.

Simple, huh?

Of course, this isn't the end of the road for this particular task. I'll need to manipulate that ID to return some specific information from a SOQL query, but it's the key to enabling me to do what I need to do next.

By the way, this took the best part of three hours to figure out. So I'm writing this here for when I inevitably forget how to do this in the future as Salesforce dev isn't a big part of my day-to-day job.