Salesforce Real Time Scenario: 5

  


Scenario: 5

You're working as a Salesforce developer for a retail company that wants to implement a trigger to automatically assign newly created Leads to the appropriate sales representative based on their region. The company has defined specific territories and corresponding sales representatives for each region. How would you approach this scenario using Apex triggers?


Code:
// Trigger: AssignLeadToRepTrigger // Object: Lead // Purpose: Automatically assign newly created Leads to sales representatives based on region trigger AssignLeadToRepTrigger on Lead (before insert) { // Method to assign Leads to sales representatives based on region public static void assignLeadsToRep(List<Lead> newLeads) { // Map to store region and corresponding sales representative Map<String, Id> regionToRepMap = new Map<String, Id>(); // Query for region and corresponding sales representative for (Territory__c territory : [SELECT Region__c, Sales_Representative__c FROM Territory__c]) { regionToRepMap.put(territory.Region__c, territory.Sales_Representative__c); } // Iterate through new Leads to assign sales representative based on region for (Lead lead : newLeads) { if (regionToRepMap.containsKey(lead.Region__c)) { lead.OwnerId = regionToRepMap.get(lead.Region__c); } else { // Default assignment if region is not found lead.OwnerId = 'Default Sales Representative Id'; } } } // Trigger handler method public static void beforeInsert(List<Lead> newLeads) { assignLeadsToRep(newLeads); } }

Evaluation
  • The candidate provides a well-structured Apex trigger named AssignLeadToRepTrigger that executes before the insertion of Lead records.
  • They effectively use SOQL queries to query Territory records and populate a map of region-to-sales representative mappings.
  • The code iterates through new Lead records and assigns the appropriate sales representative based on the lead's region, utilizing the region-to-sales representative map.
  • In cases where a region is not found in the mapping, the code provides a default assignment to a default sales representative.
  • The trigger handler method beforeInsert calls the assignLeadsToRep method, maintaining separation of concerns and promoting code maintainability.
  •  Stay tuned for more tutorials and join our community SFDC Telugu! 

    Apex Programs PDF Free Downloads For Channel Members Join Channel Membership 

    For more detailed explanations, practical examples, and resources, refer your friends to SFDC Telugu:











  • www.sfdctelugu.in

Post a Comment

0 Comments