Erfassen Sie Ihre Fortschritte
Trailhead-Startseite
Trailhead-Startseite

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 addBonusProduct method of the OrderItemUtility class. After the addBonusProduct 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:
  6. trigger orderTrigger on Order (before update) {
        OrderItemUtility.addBonusBouquet(trigger.new);
    }
  7. 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.
  2. One order listed under the All Orders list views.

  3. In the Order Products related list, click Add Products.
  4. Make sure the Standard Price Book is selected and click Save.
  5. In the Search Products box, enter BOT and select “BOT” in Products.
  6. Select the checkbox next to a product and then click Next.
  7. Enter a quantity for the product you selected.
  8. 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.