3.1 What is a trigger

The concept of trigger

So what is a trigger? In short, trigger is the some actions you want to perform when you insert/update/delete a record in Salesforce. Think about these scenarios:

  1. When you have the original price and discount type of a merchandise, you want to directly get the discounted price of the merchandise.
  2. Customers can have balance in our system. When they spend some money, the balance will automatically subtract the amount he or she has spent.
  3. When the new customer has registered, we want to send a welcome email to him/her. In the meanwhile, we want to keep its email address in the contact list.

Some of the above scenarios can also be achieved by workflow or process builder. However, there are limitations to them:

  1. Your workflow can’t create or update a separate object!
  2. You’re not allowed to reference certain fields, like Owner.Name
  3. You need your workflow to do more than just simple field updates and emails.

Triggers don’t have such limitations. Using code has more flexibility.

The type of triggers

Let’s create a trigger in Salesforce. In Developer console, File > New > Apex Trigger. SObject type, choose Merchandise__c. And in the name field, put MerchandiseTrigger. You will get the following auto-generated code:


trigger MerchandiseTrigger on Merchandise__c (before insert) {

}

trigger Merchandise on Merchandise__c is pretty easy to understand. It is the trigger name and the SObject we have just specified. So what does before insert mean?

It means every time when you create a record in Salesforce, before the change is actually committed, this code will be executed.

Trigger type can be divided by the dml type – insert, update and delete. And also the event type – before and after. Before means before the record is actually saved in the system, after means after the record is saved. You will understand this further as we go through more examples.

One trigger can serve for multiple types. They are divided by comma. As shown below:


trigger MerchandiseTrigger on Merchandise__c (before insert, after insert, after update, before delete) {

    System.debug('Hello');

}

In the above code, System.debug(‘Hello’) will be executed each time when before and after insert, after insert and before delete happens.

Next Post

3.2 Write your first trigger

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 *