Search Here

Whenever Lead is created with LeadSource as Web then give rating as cold otherwise hot trigger in Salesforce

 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

  1. Trigger Event:

    • The trigger runs on the before insert event to update the Rating field before the lead is saved to the database.
  2. Logic:

    • If the LeadSource is 'Web', the Rating is set to 'Cold'.
    • For all other LeadSource values, the Rating is set to 'Hot'.
  3. Bulk Handling:

    • The trigger iterates over all leads in the Trigger.new collection, ensuring it handles bulk inserts.

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');
    }
}







Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.