Salesforce Real Time Scenario: 7

Scenario: 7

You're a Salesforce developer for a retail company that wants to implement a trigger to enforce a business rule on the Product object. The requirement is to ensure that the Product's price is always greater than or equal to its cost. Additionally, whenever a Product's price is updated, the system should automatically recalculate the profit margin percentage and update a custom field on the Product record. How would you approach this scenario using Apex triggers?

Code:

// Trigger: EnforceProductPriceTrigger // Object: Product // Purpose: Enforce business rule to ensure price >= cost and calculate profit margin percentage on price updates trigger EnforceProductPriceTrigger on Product (before insert, before update) { // Method to enforce business rule and calculate profit margin percentage public static void enforceBusinessRuleAndCalculateProfit(List<Product> products) { for (Product prod : products) { // Check if price is less than cost if (prod.Price__c < prod.Cost__c) { prod.addError('Product price must be greater than or equal to cost.'); } // Calculate profit margin percentage if price is updated if (Trigger.isUpdate && prod.Price__c != Trigger.oldMap.get(prod.Id).Price__c) { Decimal profitMargin = ((prod.Price__c - prod.Cost__c) / prod.Cost__c) * 100; prod.Profit_Margin__c = profitMargin; } } } // Trigger handler method public static void beforeInsertUpdate(List<Product> products) { enforceBusinessRuleAndCalculateProfit(products); } }

Evaluation:

  • The candidate provides a well-structured Apex trigger named EnforceProductPriceTrigger that executes before the insertion or update of Product records.
  • They effectively use trigger context variables to determine whether the trigger is handling an insert or update operation.
  • The code includes logic to enforce the business rule ensuring that the Product's price is greater than or equal to its cost, throwing an error message if the condition is violated.
  • Additionally, the trigger calculates the profit margin percentage and updates the custom field Profit_Margin__c whenever the Product's price is updated.
  • The trigger handler method beforeInsertUpdate calls the enforceBusinessRuleAndCalculateProfit 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.i
  • Post a Comment

    0 Comments