Skip to main content

Create and Test a Trigger

Now that we have all the business logic coded, let’s create a trigger to initiate that logic.

Create a Trigger

We create a trigger that monitors orders. When the trigger, called orderTrigger, detects a change to an order, it runs the code in the addBonusBouquet method of the OrderItemUtility class. After the addBonusBouquet code runs, the order is updated with the change that the trigger detected.

  1. In the Developer Console, click File | New | Apex Trigger. The New Apex Trigger window opens.
  2. For Name, type orderTrigger.
  3. For sObject, select Order.
  4. Click Submit.
  5. Replace the existing code with this code:
    trigger orderTrigger on Order(before update) {
        OrderItemUtility.addBonusBouquet(Trigger.new);
    }
  6. Save the trigger.

You have created a class, a method, and a trigger to automate the creation of a new order item. Time to see your hard work in action!

Test It Out

  1. In the BOTanicals app home page, find the All Orders (BOTanicals) list view, and click the order number that’s associated with Alsarraf Enterprises.

    One order listed under the All Orders list views.

  2. In the Order Products related list, click Add Products.
  3. Make sure the Standard Price Book is selected and click Save.
  4. In the Search Products box, enter BOT and press Enter (or enter BOT and click the suggested search dropdown).
  5. Select the checkbox next to a product and then click Next.
  6. Enter a quantity for the product you selected.
  7. Click Save.

Your order should be in Draft status and should include the Alsarraf Enterprises account and one order product.

Order details view displaying the current order product.

Activate Order

  1. In the Path, click Activated.
  2. Click Mark as Current Status. You should see that the order has a new item, which has a unit price of $0. If you don’t see it, refresh your browser.
  3. In the Order Products related list, click View All.

    Your list should look something like this. The FREE Bouquet was automatically added to the order.

    List of Order Products. One Wonderful White Standard Bouquet (which we ordered) and One Beautiful Blue Standard Bouquet (which was automatically added to the order as a bonus product.

Congratulations! You’ve coded a business process that adds a bonus orderItem to an activated order. 

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities