Here’s how you can create an Apex Trigger in Salesforce to meet the requirement of setting the Rating field on a Lead based on its LeadSource value:
trigger SetLeadRatingOnLeadSource on Lead (before insert) {
for (Lead lead : Trigger.new) {
if (lead.LeadSource == 'Web') {
lead.Rating = 'Cold';
} else {
lead.Rating = 'Hot';
}
}
}
Explanation of the Code
Trigger Event:
- The trigger runs on the
before insert
event to update theRating
field before the lead is saved to the database.
- The trigger runs on the
Logic:
- If the
LeadSource
is'Web'
, theRating
is set to'Cold'
. - For all other
LeadSource
values, theRating
is set to'Hot'
.
- If the
Bulk Handling:
- The trigger iterates over all leads in the
Trigger.new
collection, ensuring it handles bulk inserts.
- The trigger iterates over all leads in the
Best Practices
- Ensure the
Rating
field has valid picklist values (Cold
,Hot
). - Use bulkification techniques (already handled in this trigger).
- Write a test class to ensure code coverage and functionality.
@isTest
private class SetLeadRatingOnLeadSourceTest {
@isTest
static void testSetLeadRatingOnLeadSource() {
// Test Case 1: LeadSource is 'Web'
Lead webLead = new Lead(
FirstName = 'John',
LastName = 'Doe',
Company = 'Web Corp',
LeadSource = 'Web'
);
insert webLead;
Lead insertedWebLead = [SELECT Rating FROM Lead WHERE Id = :webLead.Id];
System.assertEquals('Cold', insertedWebLead.Rating, 'Rating should be set to Cold for Web LeadSource');
// Test Case 2: LeadSource is not 'Web'
Lead otherLead = new Lead(
FirstName = 'Jane',
LastName = 'Smith',
Company = 'Other Corp',
LeadSource = 'Email'
);
insert otherLead;
Lead insertedOtherLead = [SELECT Rating FROM Lead WHERE Id = :otherLead.Id];
System.assertEquals('Hot', insertedOtherLead.Rating, 'Rating should be set to Hot for non-Web LeadSource');
}
}