3.2 Write your first trigger

The scenario

In this post we are going to cover a real scenario, for each merchandise record we have created, we will automatically calculate the discount price based on original price and discount type.

The solution

Let’s open the MerchandiseTrigger we created in last post. The trigger is still empty. Let’s update the code into this:

trigger MerchandiseTrigger on Merchandise__c (before insert) {
    for(Merchandise__c mer: Trigger.New) {
        if(mer.Discount_Type__c == 'Normal price') {
            mer.Discounted_Price__c = mer.Original_Price__c;
        else if (mer.Discount_Type__c == 'Good price') {
            mer.Discounted_Price__c = mer.Original_Price__c * 0.7;
        } else if (mer.Discount_Type__c == 'Half price') {
            mer.Discounted_Price__c = mer.Original_Price__c * 0.5;

A bit explanation

If you are familiar with all the programming elements in Apex programming language, this code shouldn’t be too hard to understand. There are only two points to mention here:

  1. Trigger.New is the list of records inserted/updated into database. Please note, Salesforce don’t always run trigger once for each record. Actually, it always try to bulk handle them if possible. If a big amount of data is inserted into Salesforce all at once (like dataloader situation), Salesforce will handle 200 records in one trigger run every time.
  2. This is a before trigger, so it is before the dml actually happends. As a result, if we update the records in trigger.new, it will result in the data being updated in the cloud database.

We can do a bit test for this trigger. Now let’s create a new merchandise record in Salesforce. Name: clothes. Original price: 100. Discount type: Good price. We can leave discount price blank. Save the record.

Notice that after the saving is done, the discounted price of clothes has been automatically filled with 70.

Next Post

3.3 Considerations of writing triggers and some best practice

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *