Add an Apex Class

In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger that you’ll be adding in the next step.
Prerequisites:
  • A Salesforce account in a sandbox Professional, Enterprise, Performance, or Unlimited Edition org, or an account in a Developer org.
  • The Book custom object.
  1. From Setup, enter “Apex Classes” in the Quick Find box, then select Apex Classes and click New.
  2. In the class editor, enter this class definition:
    public class MyHelloWorld {
    
    }
    The previous code is the class definition to which you’ll be adding one method in the next step. Apex code is contained in classes. This class is defined as public, which means the class is available to other Apex classes and triggers. For more information, see Classes, Objects, and Interfaces.
  3. Add this method definition between the class opening and closing brackets.
    public static void applyDiscount(Book__c[] books) {
       for (Book__c b :books){
          b.Price__c *= 0.9;
       }
    }

    This method is called applyDiscount, and it’s both public and static. Because it’s a static method, you don't need to create an instance of the class to access the method—you can use the name of the class followed by a dot (.) and the name of the method. For more information, see Static and Instance Methods, Variables, and Initialization Code.

    This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the object name Book__c. This indicates that it’s a custom object that you created. Standard objects that are provided in the Salesforce application, such as Account, don't end with this postfix.

    The next section of code contains the rest of the method definition:

    for (Book__c b :books){
       b.Price__c *= 0.9;
    }

    Notice the __c after the field name Price__c. This indicates that it’s a custom field that you created. Standard fields that are provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name doesn't end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c, multiplies it by 0.9, which means its value is discounted by 10%, and then stores the new value into the b.Price__c field. The *= operator is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See Expression Operators.

  4. Click Save to save the new class. You now have this full class definition.
    public class MyHelloWorld {
       public static void applyDiscount(Book__c[] books) {
          for (Book__c b :books){
             b.Price__c *= 0.9;
          }
       }
    }
You now have a class that contains some code that iterates over a list of books and updates the Price field for each book. This code is part of the applyDiscount static method called by the trigger that you’ll create in the next step.