To update the Description field on an Opportunity based on its Stage whenever the Stage is updated or the Opportunity is created, you can create an Apex Trigger on the Opportunity object. The trigger will check the Stage value and populate the Description field accordingly.
Here’s the code for the trigger:
trigger UpdateOpportunityDescription on Opportunity (before insert, before update) {
// Loop through the Opportunity records being inserted or updated
for (Opportunity opp : Trigger.new) {
// Check the Stage value and set the Description field accordingly
if (opp.StageName == 'Closed Lost') {
opp.Description = 'Opp is Closed Lost';
} else if (opp.StageName == 'Closed Won') {
opp.Description = 'Opp is Closed Won';
} else if (opp.StageName == 'Open') {
opp.Description = 'Opp is Open';
} else {
opp.Description = ''; // Clear the Description for other stages if necessary
}
}
}
Explanation of the Code
Trigger Event:
- The trigger runs on the
before insert
andbefore update
events. This ensures that the Description field is updated before the Opportunity is saved.
- The trigger runs on the
Logic:
- The trigger checks the StageName field of the Opportunity:
- If the Stage is Closed Lost, it sets the Description field to 'Opp is Closed Lost'.
- If the Stage is Closed Won, it sets the Description field to 'Opp is Closed Won'.
- If the Stage is Open, it sets the Description field to 'Opp is Open'.
- If the Opportunity is in any other Stage, you can optionally clear the Description field or leave it as-is.
- The trigger checks the StageName field of the Opportunity:
Bulk Processing:
- The trigger is bulkified, meaning it can handle multiple Opportunities in a single transaction.