50 Salesforce Apex trigger scenarios categorized by complexity to help you practice coding real-world business logic

 Beginner Scenarios (Basic Automation & Validations)

  1. Lead Automation: Automatically set the Rating to "Hot" whenever a new Lead is created with an Industry of "Technology".
  2. Account Phone Cascade: Update the Phone field on all related Contacts whenever the parent Account’s Phone is modified.
  3. Prevent Deletion: Restrict users from deleting an Opportunity if its StageName is already set to "Closed Won".
  4. Task Creation: Automatically create a follow-up Task for the Account owner whenever a new Account of type "Prospect" is created.
  5. Contact Greeting: Set a custom Description text (e.g., "Hello [FirstName]") on a Contact record right before it is inserted.
  6. Case Priority: Automatically upgrade a Case Priority to "High" if the subject contains the word "Urgent" or "Critical".
  7. Opportunity Defaulting: Set the CloseDate to exactly 30 days from today whenever a new Opportunity is created without one.
  8. Account Description: Populate the Account Description with "Created by [User Name] on [Date]" during the insert operation.
  9. Lead Source Validation: Prevent a Lead from being saved if the LeadSource is blank and the status is set to "Working - Contacted".
  10. Contact Email Enforcement: Throw an error if a user attempts to create a Contact without providing either a Phone or an Email.
  11. Opportunity Line Item Check: Block users from changing an Opportunity StageName to "Closed Won" if it has zero line items.
  12. Account Annual Revenue: Automatically change the CustomerPriority__c custom picklist to "High" if AnnualRevenue exceeds $1,000,000.
  13. Case Origin Routing: Automatically assign a Case to a specific regional queue based on the Web_Country__c field value upon creation.
  14. Contact Mailing Address: Copy the parent Account's BillingAddress fields to the Contact's MailingAddress fields if left blank during creation.
  15. Prevent Account Duplicate: Throw a custom error if a user tries to create a new Account with an AccountName that already exists in the system. 
Intermediate Scenarios (Related Records & Complex Logic)
  1. Opportunity Rollup Summary: Calculate the total amount of all open Opportunities on an Account and store it in a custom Account field Total_Open_Amount__c (upon insert, update, delete, or undelete).
  2. Contact Primary Flag: Ensure that only one Contact related to an Account can be marked as Is_Primary__c. If a new one is checked, uncheck the old one.
  3. Account Team Automation: Automatically add the Account creator's manager to the Account Team with "Read/Write" access upon Account creation.
  4. Case SLA Breached Trigger: When a Case Status changes to "Escalated", automatically update a custom flag on the parent Account called Has_Escalated_Cases__c.
  5. Asset Creation: Automatically generate an Asset record for every OpportunityLineItem added when an Opportunity is successfully marked "Closed Won".
  6. Prevent Contact Orphanage: Prevent a Contact from being updated if its AccountId is removed (ensure Contacts cannot be orphaned if they started with an Account).
  7. Opportunity Stage History Tracking: Create a record in a custom object Stage_History_Log__c every time an Opportunity's StageName changes, tracking old and new values.
  8. Account VIP Status: If an Account's total closed-won opportunity revenue drops below $500,000 (due to a deleted or modified opportunity), downgrade its custom Tier__c status.
  9. Contact Sharing Rule: Dynamically share a Contact record with a public group matching the Contact's Department using ContactShare.
  10. Lead Conversion Custom Mapping: Write a trigger on Lead conversion that bypasses standard mapping to parse a multi-select picklist into specific related custom object records.
  11. Quote Synchronization: Ensure that when a custom Quote__c object is marked as "Accepted", all other quotes under the same Opportunity are automatically marked "Rejected".
  12. Campaign Member Status: Automatically update the Status of a CampaignMember to "Responded" if a related Task is marked "Completed".
  13. Prevent Multi-Owner Changes: Prevent a single bulk transaction from changing the owner of Accounts if the records belong to more than three different profiles.
  14. Case Dynamic Entitlement: Assign a specific Entitlement record to a Case automatically based on the Account’s service contract type upon Case insertion.
  15. Account Total Contacts Count: Build a custom rollup trigger that counts total related Contacts on an Account and stores it in Total_Contacts__c without using rollup summary fields.
  16. Opportunity Partner Creation: Automatically create an Opportunity Partner record if a custom lookup field Referring_Partner__c is populated on Opportunity creation.
  17. Contact Birthday Notification: Create a Task for the Contact owner 7 days before the Contact's Birthdate occurs.
  18. Contract Expiration Task: Automatically generate a renewal Opportunity 90 days before a Contract reaching its EndDate.
  19. Case Close Restriction: Block a Case from being closed if there are any related custom Work_Order__c records still in an "Open" status.
  20. Product Price Validation: Prevent an OpportunityLineItem from being added if its unit price is 20% lower than the standard List Price in the Pricebook. 
Advanced Scenarios (Bulkification, Maps, Contexts & Apex Best Practices)
  1. Recursive Trigger Prevention: Write a scenario where updating an Account updates its Contacts, which triggers a Contact update that modifies the Account. Implement a utility class to block this recursion.
  2. Apex Managed Sharing on Account: When an Account's custom Regional_Manager__c lookup field changes, delete the old sharing row (AccountShare) and programmatically add a new one for the new manager.
  3. Prevent Recursive Field Loops: Prevent an infinite loop when an update to Field A automatically forces an update to Field B, which by business logic modifies Field A again.
  4. Bulk Merge Logic: Write a trigger on Account delete that identifies if it is being merged, and moves specific custom child logs to the master Account safely under high volume.
  5. Async Gateway Trigger: When a Case is marked "Sync Needed", call an @future method or Queueable class from the trigger to pass Case payloads to an external system (handling callout limits).
  6. Opportunity Split Automation: Automatically create custom Revenue_Split__c records dividing credit 60/40 between the Opportunity Owner and an Overlay Sales Rep based on zip codes.
  7. Contact Status Pipeline: Build a trigger that tracks the duration a Contact spends in each Status picklist value by updating a related child history tracking table.
  8. Account Deactivation Cascade: When an Account Status__c is changed to "Inactive", change all related Contacts to "Inactive", close all open Opportunities as "Closed Lost", and close open Cases.
  9. Dynamic Pricebook Assignment: Based on the User's operating country and the Account's currency, dynamically attach the correct custom Pricebook2Id to an Opportunity before it saves.
  10. Bypass Trigger framework: Implement a custom metadata or hierarchical custom setting check at the very top of your trigger handler to allow administrators to turn off triggers dynamically for data loads.
  11. ContentDocumentLink Verification: Write a trigger on ContentDocumentLink to prevent files from being uploaded to a "Closed Won" Opportunity unless the user has an Admin profile.
  12. Order and OrderItem Sync: When an Order status shifts to "Activated", ensure that all child OrderItem quantities are verified against live external inventory using a queueable chain.
  13. User Profile Lock: Write a trigger on the User object that automatically deactivates related custom contact portal records if the internal corporate user is deactivated.
  14. Lead Duplication Deduper: When a bulk batch of Leads is inserted via Data Loader, use Maps and Sets to cross-verify emails against existing Leads AND against other records within the same batch payload to throw a clean error.
  15. Custom Rollup with Multi-Currency: Write a trigger to calculate total Opportunity amounts onto the Account record while dynamically handling conversion rates if the organization utilizes Salesforce Multi-Currency. 

Comments

Popular posts from this blog

Multi currency in Salesforce - Revenue Cloud Advance - Revenue Lifecycle Management

Create the Callout Step in DRO - Salesfroce - Dynamic Revenue Orchestrator

Apex Triggers - 15 (Amazon Interview Question)