Here’s an Apex Trigger that sets the Description field on an Opportunity to Hot Opportunity
when the Amount is not null and greater than 100,000
during Opportunity creation.
trigger SetDescriptionForHotOpportunity on Opportunity (before insert) {
for (Opportunity opp : Trigger.new) {
// Check if Amount is not null and greater than 100,000
if (opp.Amount != null && opp.Amount > 100000) {
opp.Description = 'Hot Opportunity';
}
}
}
Explanation of the Code
Trigger Event:
- The trigger is written for the
before insert
event since the Description field needs to be populated before the record is saved.
- The trigger is written for the
Logic:
- Checks if the Amount field is not null and greater than
100,000
. - If the condition is true, the Description field is set to
'Hot Opportunity'
.
- Checks if the Amount field is not null and greater than
Bulk Processing:
- The trigger iterates over all records in
Trigger.new
to ensure it works for bulk inserts.
@isTest
private class SetDescriptionForHotOpportunityTest {
@isTest
static void testSetDescriptionForHotOpportunity() {
// Test Case 1: Opportunity with Amount > 100,000
Opportunity highValueOpp = new Opportunity(
Name = 'High Value Deal',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 150000
);
insert highValueOpp;
// Query the inserted Opportunity
Opportunity insertedHighValueOpp = [SELECT Description FROM Opportunity WHERE Id = :highValueOpp.Id];
System.assertEquals('Hot Opportunity', insertedHighValueOpp.Description, 'Description should be set to Hot Opportunity for Amount > 100,000');
// Test Case 2: Opportunity with Amount <= 100,000
Opportunity lowValueOpp = new Opportunity(
Name = 'Low Value Deal',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 50000
);
insert lowValueOpp;
// Query the inserted Opportunity
Opportunity insertedLowValueOpp = [SELECT Description FROM Opportunity WHERE Id = :lowValueOpp.Id];
System.assert(insertedLowValueOpp.Description == null, 'Description should remain null for Amount <= 100,000');
// Test Case 3: Opportunity with null Amount
Opportunity nullAmountOpp = new Opportunity(
Name = 'No Amount Deal',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert nullAmountOpp;
// Query the inserted Opportunity
Opportunity insertedNullAmountOpp = [SELECT Description FROM Opportunity WHERE Id = :nullAmountOpp.Id];
System.assert(insertedNullAmountOpp.Description == null, 'Description should remain null if Amount is not provided');
}
}