Salesforce Apex Triggers for Beginners: Change the Stage when an Opportunity is created.
Requirement: Write a Salesforce Apex Trigger to change the Stage/default the stage to ‘Prospecting’ when an Opportunity is created. In other words, when an Opportunity is created by selecting any Stage, the Stage should default back to Prospecting.
Lets start by revisiting the Salesforce Apex Trigger Syntax:
trigger *triggerName* on *Object* (*before/after event*) { for (*Object* *Variable* : Trigger.New) **Trigger Actions & Code Block** }
We will write the trigger in the following three Steps:
- Define the trigger
- Build a ‘For Each’ loop to iterate through each record
- Update the Stage
Now lets write each Step for this trigger.
The complete Trigger to change the Stage when Opportunity is Created would be:
//Defining the Trigger - Trigger Name, Object and Events. trigger DefaultStageProspecting on Opportunity (before insert) { //For each Opportunity record being updated, assign the variable 'Opp' to it. for ( Opportunity Opp :Trigger.New) { // Update the Stage to 'Prospecting' Opp.StageName = 'Prospecting'; } }
This is how the Trigger looks in the Developer Console (Image)
Leave a Reply