50 Salesforce Apex trigger scenarios categorized by complexity to help you practice coding real-world business logic
Beginner Scenarios (Basic Automation & Validations)
- Lead Automation: Automatically set the
Ratingto "Hot" whenever a new Lead is created with anIndustryof "Technology". - Account Phone Cascade: Update the
Phonefield on all related Contacts whenever the parent Account’sPhoneis modified. - Prevent Deletion: Restrict users from deleting an Opportunity if its
StageNameis already set to "Closed Won". - Task Creation: Automatically create a follow-up Task for the Account owner whenever a new Account of type "Prospect" is created.
- Contact Greeting: Set a custom
Descriptiontext (e.g., "Hello [FirstName]") on a Contact record right before it is inserted. - Case Priority: Automatically upgrade a Case
Priorityto "High" if the subject contains the word "Urgent" or "Critical". - Opportunity Defaulting: Set the
CloseDateto exactly 30 days from today whenever a new Opportunity is created without one. - Account Description: Populate the Account
Descriptionwith "Created by [User Name] on [Date]" during the insert operation. - Lead Source Validation: Prevent a Lead from being saved if the
LeadSourceis blank and the status is set to "Working - Contacted". - Contact Email Enforcement: Throw an error if a user attempts to create a Contact without providing either a
Phoneor anEmail. - Opportunity Line Item Check: Block users from changing an Opportunity
StageNameto "Closed Won" if it has zero line items. - Account Annual Revenue: Automatically change the
CustomerPriority__ccustom picklist to "High" ifAnnualRevenueexceeds $1,000,000. - Case Origin Routing: Automatically assign a Case to a specific regional queue based on the
Web_Country__cfield value upon creation. - Contact Mailing Address: Copy the parent Account's
BillingAddressfields to the Contact'sMailingAddressfields if left blank during creation. - Prevent Account Duplicate: Throw a custom error if a user tries to create a new Account with an
AccountNamethat already exists in the system.
Intermediate Scenarios (Related Records & Complex Logic)
- 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). - 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. - Account Team Automation: Automatically add the Account creator's manager to the Account Team with "Read/Write" access upon Account creation.
- Case SLA Breached Trigger: When a Case
Statuschanges to "Escalated", automatically update a custom flag on the parent Account calledHas_Escalated_Cases__c. - Asset Creation: Automatically generate an
Assetrecord for everyOpportunityLineItemadded when an Opportunity is successfully marked "Closed Won". - Prevent Contact Orphanage: Prevent a Contact from being updated if its
AccountIdis removed (ensure Contacts cannot be orphaned if they started with an Account). - Opportunity Stage History Tracking: Create a record in a custom object
Stage_History_Log__cevery time an Opportunity'sStageNamechanges, tracking old and new values. - 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__cstatus. - Contact Sharing Rule: Dynamically share a Contact record with a public group matching the Contact's
DepartmentusingContactShare. - 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.
- Quote Synchronization: Ensure that when a custom
Quote__cobject is marked as "Accepted", all other quotes under the same Opportunity are automatically marked "Rejected". - Campaign Member Status: Automatically update the
Statusof aCampaignMemberto "Responded" if a related Task is marked "Completed". - 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.
- Case Dynamic Entitlement: Assign a specific
Entitlementrecord to a Case automatically based on the Account’s service contract type upon Case insertion. - Account Total Contacts Count: Build a custom rollup trigger that counts total related Contacts on an Account and stores it in
Total_Contacts__cwithout using rollup summary fields. - Opportunity Partner Creation: Automatically create an Opportunity Partner record if a custom lookup field
Referring_Partner__cis populated on Opportunity creation. - Contact Birthday Notification: Create a Task for the Contact owner 7 days before the Contact's
Birthdateoccurs. - Contract Expiration Task: Automatically generate a renewal Opportunity 90 days before a
Contractreaching itsEndDate. - Case Close Restriction: Block a Case from being closed if there are any related custom
Work_Order__crecords still in an "Open" status. - Product Price Validation: Prevent an
OpportunityLineItemfrom 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)
- 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.
- Apex Managed Sharing on Account: When an Account's custom
Regional_Manager__clookup field changes, delete the old sharing row (AccountShare) and programmatically add a new one for the new manager. - 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.
- 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.
- Async Gateway Trigger: When a Case is marked "Sync Needed", call an
@futuremethod or Queueable class from the trigger to pass Case payloads to an external system (handling callout limits). - Opportunity Split Automation: Automatically create custom
Revenue_Split__crecords dividing credit 60/40 between the Opportunity Owner and an Overlay Sales Rep based on zip codes. - Contact Status Pipeline: Build a trigger that tracks the duration a Contact spends in each
Statuspicklist value by updating a related child history tracking table. - Account Deactivation Cascade: When an Account
Status__cis changed to "Inactive", change all related Contacts to "Inactive", close all open Opportunities as "Closed Lost", and close open Cases. - Dynamic Pricebook Assignment: Based on the User's operating country and the Account's currency, dynamically attach the correct custom
Pricebook2Idto an Opportunity before it saves. - 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.
- ContentDocumentLink Verification: Write a trigger on
ContentDocumentLinkto prevent files from being uploaded to a "Closed Won" Opportunity unless the user has an Admin profile. - Order and OrderItem Sync: When an
Orderstatus shifts to "Activated", ensure that all childOrderItemquantities are verified against live external inventory using a queueable chain. - User Profile Lock: Write a trigger on the
Userobject that automatically deactivates related custom contact portal records if the internal corporate user is deactivated. - 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.
- 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
Post a Comment