Teach Me Salesforce

A community approach to learning salesforce.com

Author Archive

Trigger to create a new record

with 13 comments

Ask me a year ago, and I never thought I’d be writing triggers, but yet, here I am. I gained a bit of confidence after taking the Salesforce DEV 531 class, and that confidence then flourished with the support of this community. This blog just goes to show how many people out there are willing to help, and I definitely want to return the favor whenever possible. So here goes – the anatomy of my first trigger.

What I was looking to do was to create a new support request record (a custom object) when a new Event record of a specific type was created. Pretty straight-forward, but definitely not doable without a trigger. The final result was this:

trigger createPDtask on Event (after insert) {     
List<Support_Request__c> sr = new List<Support_Request__c>();
    for (Event newEvent: Trigger.New)
         if (newEvent.Type__c == '1. Meeting - Initial'){
                 sr.add (new Support_Request__c(
                     Name = 'New PD',
                     Task_Type__c = 'PD',
                     SFDC_Record_ID__c = newEvent.Id,
                     Rep__c = newEvent.OwnerId,
                     Event_Date__c = newEvent.ActivityDate));   
         }
   insert sr;
 }

Now for the breakdown of what I was trying to do with each step. First, I define what I want the trigger to do & when to do it.

trigger createPDtask on Event (after insert) {

The second line compiles all new records I am going to insert into a list (& therefore takes care of bulkifying my trigger).

List<Support_Request__c> sr = new List<Support_Request__c>();

Then I need to define the criteria around the event record that would cause this trigger to create a new support request.

for (Event newEvent: Trigger.New)
         if (newEvent.Type__c == '1. Meeting - Initial'){

Next, I set the details that get inserted into the new Support Request record. You can see that some are static, while a few are dynamically pulled from the event record.

sr.add (new Support_Request__c(
                     Name = 'New PD',
                     Task_Type__c = 'PD',
                     SFDC_Record_ID__c = newEvent.Id,
                     Rep__c = newEvent.OwnerId,
                     Event_Date__c = newEvent.ActivityDate));

Finally, the list gets inserted.

 }
   insert sr;
 }

As far as triggers goes, it’s pretty simple, but it was a great learning process for me to build on my own. From here, the next step is to write some test coverage, and while I thought I had it in the bag, I’m going to let Kyle share the lesson he gave me in a subsequent post.

Advertisements

Written by Becka

May 16, 2011 at 10:10 am

Posted in Apex, Beginner, Intermediate, Trigger

Tagged with