Trigger to change the Stage when Opportunity is Created – Triggers for Beginners

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:

  1. Define the trigger
  2. Build a ‘For Each’ loop to iterate through each record
  3. Update the Stage

Now lets write each Step for this trigger.

//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';

    }
}

 

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)

Trigger to Update StageName
Trigger to Update StageName

 

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.