Introduction to Triggers

Video Overview

Watch the video above to get an idea of how to write a basic trigger, and what some of the important things are to know when writing a trigger.

Code to the very simple trigger written is as follows — this code may look familiar if you’ve watched the video or read the post about Workflow Rules.

trigger SetContactDeadline on Lead (before insert) {
    // can be before/after insert, before/after update!
    // these are the most common scenarios.
    // First, any queries - keep them outside of the loop. 
    BusinessHours bh = [
        SELECT Id
        FROM BusinessHours
        WHERE Name = 'My Business Hours'
    // Now, let's loop through the records passed by the Trigger!
    // Remember, it can be multiple records
    for (Lead newLead: {
        Datetime nowDate =;
        Long interval = 24*60*60*1000; // Remember, this is in milliseconds - 1000 ms * 60 secs * 60 mins * 24 (business) hours!

		// To calculate the "deadline," we will add that interval using BusinessHours.add
        Datetime expireDate = BusinessHours.add(bh.Id, nowDate, interval);
        // Last, let's set the field value. 
        newLead.Prompt_Contact_By__c = expireDate;
		// That's all! Remember, since it is already running "before insert," we don't need to do any DML operations!

A few notes…
  • For your application, you may need to choose a different time for the trigger to run — as I mention in the video, before or after insert and before or after update are common choices.
  • Never query inside of the loop!
  • Be careful with your DML – you can’t update a record that hasn’t been inserted yet, and you wouldn’t want to try to insert a record which is only being updated!

Until next time, cheers!

Add comment

Recent Posts