Start tracking your progress
Trailhead Home
Trailhead Home

Add a Method to the Class

Create a Method

A class usually contains one or more methods that do something useful. In this step, you’ll create the updateOlderAccounts method, which gets the first five Account records ordered by the date created. It then updates the description field to say that this is a “heritage account,” meaning accounts that are older than other accounts.

  1. In the body of the OlderAccountsUtility class (the information between the curly brackets), copy and paste the following method.
        public static void updateOlderAccounts() {
          // Get the 5 oldest accounts
          Account[] oldAccounts = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
          // loop through them and update the Description field
          for (Account acct : oldAccounts) {
              acct.Description = 'Heritage Account';
          }
          // save the change you made
          update oldAccounts;
        }
    
  2. Click File | Save.

The code first sorts Accounts by the date that they were created on. It then grabs the five oldest records. It uses the SOQL query language (line 3) to do the querying and sorting. It then iterates through each Account record to update the Description field. Finally, it updates the Account records by using the Apex Data Manipulation Language (DML). If you're familiar with Java and C#, you'll notice a lot of similarity in the syntax.