Working with Triggers
Triggers implement event-driven logic that executes automatically when specific entity records are created, updated, or deleted within the Magentrix platform. These automated code components enable implementation of complex business rules, data validation, automated notifications, calculated field updates, and integration workflows that respond to data changes throughout the portal ecosystem without requiring manual user actions or intervention.
Understanding trigger functionality, creation processes, appropriate use cases, and implementation best practices enables developers to build sophisticated automated business logic that maintains data integrity, enforces organizational policies, and streamlines business processes through event-driven architecture patterns.
Understanding Trigger Purpose and Function
Event-Driven Execution Model
Triggers operate on an event-driven execution model where code executes automatically in response to specific data manipulation operations on entity records. The Magentrix platform invokes triggers at appropriate points during record lifecycle events without requiring explicit method calls or user-initiated actions.
Create Events: Triggers can execute when new entity records are created, enabling validation of initial data, setting default field values, creating related records automatically, sending notifications about new records, and initializing calculated fields based on input values.
Update Events: Triggers execute when existing entity records are modified, enabling detection of field value changes, recalculation of dependent fields, validation of updated values against business rules, triggering of downstream processes based on status changes, and notification of stakeholders about important updates.
Delete Events: Triggers can execute before or after entity records are deleted, enabling prevention of deletions that violate business rules, cleanup of related records, archiving of deleted data, notification of stakeholders about deletions, and validation that deletions meet organizational requirements.
Automatic Invocation
The Magentrix platform automatically identifies and invokes appropriate triggers when data manipulation operations occur. Developers do not explicitly call trigger code; instead, the platform's event processing infrastructure handles trigger execution based on entity associations and event types.
Transparent Execution: Users and client applications remain unaware of trigger execution. Triggers operate behind the scenes, performing necessary validation, calculations, and side effects while the user experiences seamless data operations.
Transaction Integration: Trigger execution occurs within the same database transaction as the data operation that triggered it. If trigger logic identifies errors or business rule violations, the entire transaction including the triggering data change can be rolled back, maintaining data consistency.
Multiple Triggers per Entity
The Magentrix platform supports creating multiple triggers for the same entity, enabling separation of concerns and modular implementation of different business rules. Multiple triggers execute in sequence during event processing, with each trigger performing its designated functionality.
Separation of Concerns: Different business rules and automated processes can be implemented in separate triggers rather than combining all logic into a single large trigger. Separation improves code organization, maintainability, and testability.
Independent Functionality: Each trigger should focus on a specific aspect of business logic such as validation, notification, related record creation, or calculation. Independent triggers enable selective enabling, disabling, or modification of specific functionality without affecting other business rules.
Multiple Triggers per Entity
The Magentrix platform supports creating multiple triggers for the same entity, enabling separation of concerns and modular implementation of different business rules. When multiple triggers exist for the same entity and event type, they all execute during event processing, with each trigger performing its designated functionality.
Separation of Concerns: Different business rules and automated processes can be implemented in separate triggers rather than combining all logic into a single large trigger. Separation improves code organization, maintainability, and testability.
Independent Functionality: Each trigger should focus on a specific aspect of business logic such as validation, notification, related record creation, or calculation. Independent triggers enable selective enabling, disabling, or modification of specific functionality without affecting other business rules.
No Guaranteed Execution Order: When multiple triggers exist for the same entity, there is no guarantee regarding the order in which triggers execute. Triggers should be designed to function independently without relying on other triggers having executed first or having modified data in specific ways.
Independent Trigger Design: Design triggers to be self-contained and independent. Each trigger should validate its own prerequisites, check for necessary field values, and implement complete logic without assuming that other triggers have already executed or prepared data in specific states.
Avoid Inter-Trigger Dependencies: Do not create triggers that depend on other triggers having executed first, modified specific fields, or established certain conditions. Inter-trigger dependencies create fragile implementations that may fail unpredictably when execution order varies or when triggers are added, removed, or modified.
Creating Triggers
Accessing Trigger Creation
Navigate to the File menu in the IDE and select New Trigger to open the trigger creation dialog. The trigger creation interface requests specific information about the trigger's identity and the entity it will monitor.
Required Field Configuration
Name Field: Enter a descriptive name for the trigger that clearly indicates its purpose and functionality. Trigger names should communicate the business rule or automated process that the trigger implements.
The system automatically appends "Trigger" to the entered name to create the final class name. For example, entering "AccountValidation" results in a trigger class named "AccountValidationTrigger." This automatic suffix ensures consistent naming across all triggers and distinguishes trigger classes from other code types.
Entity Selection: Select the Entity from the dropdown list that this trigger will monitor for data changes. The entity selection determines which record type will cause this trigger to execute when create, update, or delete operations occur.
The dropdown displays all available entities in the Magentrix platform including standard entities (Account, Contact, User, etc.) and custom entities defined in the organization. Entity names in the dropdown reflect the exact API names that must be used in code.
Trigger Creation Completion
Click Create to generate the new trigger. The IDE creates the trigger file with the automatically constructed name (original name plus "Trigger" suffix), adds it to the Triggers section in the sidebar navigation tree, and opens the trigger in a new tab in the editor workspace.
Initial Structure: Newly created triggers contain basic class structure including namespace declarations, using statements for Magentrix SDK components, entity association configuration, and empty trigger context methods ready for business logic implementation.
Entity Association: The trigger's association with the selected entity is configured in the trigger class structure. This association ensures the platform invokes the trigger when appropriate operations occur on records of that entity type.
Trigger Naming and Management
Automatic Naming Convention
Trigger names follow a mandatory convention where "Trigger" is automatically appended to the name entered during creation. This suffix cannot be omitted or customized and ensures consistent identification of trigger classes throughout the codebase.
Descriptive Naming: Choose trigger names that clearly communicate the business rule or automated process implemented by the trigger. Names like "AccountValidation," "ContactEmailNotification," "OpportunityCalculation," or "CaseAssignment" immediately indicate trigger purpose.
Entity Reference: Consider including the entity name in the trigger name to enable quick identification of which entity the trigger monitors. This practice becomes particularly valuable when working with numerous triggers across multiple entities.
Purpose Indication: Include action indicators in trigger names such as "Validation," "Notification," "Assignment," "Calculation," or "Synchronization" to communicate the trigger's primary function at a glance.
Renaming Triggers
Triggers can be renamed after creation through standard IDE file renaming operations. When a trigger is renamed, both the file name and the internal class name update to reflect the new name while maintaining the "Trigger" suffix.
No Reference Impact: Renaming triggers does not affect existing code or references because triggers are not explicitly called from other code. The platform invokes triggers based on entity associations and event types rather than class name references.
Identification Purpose: Trigger names serve primarily for developer identification, organization, and understanding. Descriptive names improve code maintainability and enable developers to quickly locate appropriate triggers when reviewing or modifying business rules.
Multiple Triggers per Entity
The Magentrix platform supports creating multiple triggers for the same entity, enabling separation of concerns and modular implementation of different business rules. When multiple triggers exist for the same entity and event type, they all execute during event processing, with each trigger performing its designated functionality.
Functional Organization: Name triggers based on functional areas such as "AccountValidationTrigger," "AccountNotificationTrigger," and "AccountCalculationTrigger" to clearly separate validation logic, notification logic, and calculation logic into independent triggers.
Separation of Concerns: Different business rules and automated processes can be implemented in separate triggers rather than combining all logic into a single large trigger. Separation improves code organization, maintainability, and testability.
Independent Functionality: Each trigger should focus on a specific aspect of business logic such as validation, notification, related record creation, or calculation. Independent triggers enable selective enabling, disabling, or modification of specific functionality without affecting other business rules.
No Guaranteed Execution Order: When multiple triggers exist for the same entity, there is no guarantee regarding the order in which triggers execute. Triggers should be designed to function independently without relying on other triggers having executed first or having modified data in specific ways.
Independent Trigger Design: Design triggers to be self-contained and independent. Each trigger should validate its own prerequisites, check for necessary field values, and implement complete logic without assuming that other triggers have already executed or prepared data in specific states.
Avoid Inter-Trigger Dependencies: Do not create triggers that depend on other triggers having executed first, modified specific fields, or established certain conditions. Inter-trigger dependencies create fragile implementations that may fail unpredictably when execution order varies or when triggers are added, removed, or modified.
Opening and Editing Triggers
Accessing from Sidebar Navigation
Navigate to the Triggers section in the sidebar navigation tree. This dedicated section contains all triggers organized by entity association or alphabetically by trigger name depending on IDE configuration.
Expand the Triggers section if necessary to display all available triggers. Triggers may be grouped by associated entity or displayed in a flat list depending on the number of triggers and IDE settings.
Double-Click Opening: Double-click on any trigger name to open that trigger file in a new tab in the editor workspace. This method provides the fastest access for editing trigger logic.
Right-Click Context Menu: Right-click on any trigger name to display a context menu with available actions. Select Open from the context menu to open the trigger file in a new tab, maintaining consistency with other IDE element opening workflows.
Code Editor Interface
Triggers open in the code editor with syntax highlighting for C# code. The editor provides line numbering, code folding for methods and classes, and find/replace functionality for efficient code editing.
Syntax Highlighting: The editor automatically highlights C# keywords, strings, comments, and other language elements using visual color differentiation. Syntax highlighting improves code readability and helps identify syntax errors during development.
Trigger Structure: Trigger files display the entity association configuration, trigger context methods for different event types (before insert, after insert, before update, after update, before delete, after delete), and any helper methods or properties implemented in the trigger class.
Multiple Trigger Editing
The IDE supports opening multiple triggers simultaneously in separate tabs along with controllers, classes, Active Pages, and other development elements. Each open trigger tab maintains independent editing state with its own undo history and unsaved changes tracking.
Cross-Trigger Reference: Multiple open tabs enable viewing multiple trigger implementations simultaneously for comparison, reviewing related triggers that work together on the same entity, or examining implementation patterns across different entities.
Entity Browser Integration: While editing triggers, access the Entity Browser to verify field names, data types, and relationships for the trigger's associated entity. The Entity Browser provides authoritative reference information without leaving the trigger editing context.
Implementing Trigger Logic
Trigger Context Methods
Triggers implement specific methods that execute at different points in the record lifecycle. The Magentrix platform provides trigger context information including the records being processed, old values before updates, and operation metadata.
Before Insert: Executes before new records are saved to the database. Use this context to validate initial field values, set default values, modify field values before save, prevent record creation based on business rules, and prepare data for initial save.
After Insert: Executes after new records are successfully saved to the database and have been assigned IDs. Use this context to create related records, send notifications about new records, update related records, trigger downstream processes, and perform operations requiring the new record's ID.
Before Update: Executes before record updates are saved to the database. Use this context to validate updated field values, detect which fields changed, prevent updates based on business rules, modify field values before save, and enforce data consistency rules.
After Update: Executes after record updates are successfully saved to the database. Use this context to update related records based on changes, send notifications about updates, trigger downstream processes, create audit records, and perform operations dependent on committed changes.
Before Delete: Executes before records are deleted from the database. Use this context to prevent deletion based on business rules, verify deletion authorization, check for dependent records, prepare cleanup operations, and validate deletion requirements.
After Delete: Executes after records are successfully deleted from the database. Use this context to clean up related records, send notifications about deletions, archive deleted data, update summary records, and perform post-deletion cleanup operations.
Accessing Trigger Context
Trigger methods receive context objects containing information about the operation being performed and the records being affected. Context objects provide access to new record values, old record values (for updates), operation type, and other metadata.
New Record Values: Access field values from records being created or updated through the new record collection in trigger context. New values represent the data being saved to the database.
Old Record Values: For update operations, access previous field values through the old record collection in trigger context. Comparing old and new values enables detection of which fields changed and by how much.
Record Iteration: Triggers process multiple records simultaneously when bulk operations occur. Implement loops to iterate through all records in trigger context, applying business rules consistently across all affected records.
Field Value Modification
Before triggers (Before Insert, Before Update) can modify field values on records being processed. Modifications affect the values saved to the database, enabling triggers to enforce data standards, calculate dependent fields, or apply business rules transparently.
Direct Field Assignment: Assign new values to record fields directly in before trigger logic. Modified values are saved to the database as if the user had entered them, with no indication that trigger logic performed the modification.
Calculated Fields: Compute field values based on other field values, lookup related record data, apply formulas, or derive values from business rules. Calculated field updates ensure data consistency and reduce manual data entry requirements.
Data Standardization: Enforce consistent data formats by standardizing phone numbers, email addresses, postal codes, or other fields with expected formats. Standardization improves data quality and enables reliable reporting and analysis.
Validation and Error Prevention
Triggers can prevent data operations from completing when business rules are violated or validation fails. Preventing invalid operations maintains data integrity and enforces organizational policies without relying on user interface validation alone.
Validation Logic: Implement validation rules that check field values, verify relationships, enforce required combinations, validate against external systems, or apply complex business rules that cannot be implemented through standard validation rules.
Error Throwing: When validation fails, throw exceptions with meaningful error messages describing the validation failure. Thrown exceptions prevent the data operation from completing and display error messages to users.
Transaction Rollback: Exceptions thrown in triggers cause the entire database transaction to roll back, undoing all changes including the data operation that triggered the trigger. This rollback maintains database consistency when business rules are violated.
Creating Related Records
After triggers (After Insert, After Update) can create related records automatically based on the triggering record's data. Automatic related record creation streamlines processes and ensures required related data exists.
Dependent Record Creation: Create required child records, related tracking records, audit entries, or associated data automatically when parent records are created or updated. Automatic creation eliminates manual steps and ensures consistency.
Relationship Establishment: Set lookup field values on created records to establish relationships with the triggering record. Proper relationship establishment enables navigation between records and maintains referential integrity.
Bulk Operation Handling: When triggers process multiple records, create related records efficiently using bulk insert operations rather than individual inserts. Bulk operations reduce database round trips and improve performance.
Sending Notifications
Triggers can send email notifications automatically when significant data changes occur, keeping stakeholders informed without requiring manual notification processes.
Email Composition: Construct email messages with appropriate recipients, subjects, and body content based on triggering record data. Include relevant information from the record and related records to provide complete context.
Template Usage: Reference email templates for consistent formatting and messaging. Templates enable centralized email content management while triggers handle automated sending based on event detection.
Recipient Determination: Determine appropriate email recipients based on record ownership, related user records, role-based distribution lists, or field values containing email addresses. Dynamic recipient determination ensures notifications reach appropriate stakeholders.
Calling Classes from Triggers
Triggers should leverage classes for complex business logic, utility functions, and operations requiring reuse across multiple triggers or controllers. Calling classes from triggers promotes code reusability and maintainability.
Class Instantiation: Instantiate required classes within trigger methods and call appropriate methods with trigger context data as parameters. Classes process data and return results that triggers use to complete their operations.
Shared Business Logic: Complex validation rules, calculation algorithms, integration operations, and data transformation logic implemented in classes can be called from multiple triggers ensuring consistent behavior across different entities and trigger contexts.
Error Handling: Wrap class method calls in try-catch blocks to handle exceptions gracefully. Determine whether exceptions should prevent the triggering operation (re-throw exception) or allow the operation to proceed with error logging.
Saving and Validating Triggers
Manual Save Requirement
The IDE does not include automatic save functionality for triggers. All changes must be saved explicitly through save buttons or keyboard shortcuts. Unsaved changes are indicated visually on tab labels with markers or text styling.
Save Button: Each editor tab includes a save button in the toolbar or interface controls. Clicking this button saves the current trigger file and initiates code compilation and validation.
Keyboard Shortcuts: Standard save keyboard shortcuts (Ctrl+S on Windows/Linux, Command+S on macOS) save the active trigger file currently displayed in the editor. Keyboard shortcuts provide faster save access during active development.
Code Compilation and Validation
When saving triggers, the IDE performs automatic code compilation and validation. The C# compiler checks syntax, verifies type correctness, validates entity and field references, and identifies compilation errors that prevent trigger execution.
Validation Results: Validation results appear at the bottom of the editor workspace immediately after save operations complete. Results indicate either successful compilation or list specific errors preventing compilation.
Error Display: Compilation errors display with specific line numbers and error descriptions, enabling quick identification and correction of issues. Error messages describe the nature of problems including syntax errors, type mismatches, undefined entity or field references, and other issues.
Error Resolution: Address compilation errors systematically by reviewing error messages, navigating to specified line numbers, correcting identified issues, and saving again to re-validate. Multiple save iterations may be necessary when errors cascade from earlier issues.
Successful Compilation: When validation completes without errors, a success indicator confirms that trigger code compiles correctly and is ready for execution. Successful compilation does not guarantee correct business logic or expected behavior, only that syntax and types are valid.
Common Trigger Compilation Errors
Entity and Field Name Errors: Incorrect entity or field names (often due to case-sensitivity) cause compilation errors when trigger code attempts to access non-existent entities or fields. Use the Entity Browser to verify correct names before coding references.
Type Mismatches: Attempting to assign incompatible types to fields, comparing fields of different types, or passing incorrect parameter types to methods causes type mismatch errors. Verify field data types in the Entity Browser before implementing trigger logic.
Context Access Errors: Incorrect access to trigger context objects, attempting to access old values in insert triggers, or misusing trigger context methods generates errors. Review trigger context documentation and ensure appropriate context access for the trigger event type.
Deleting Triggers
Deletion Process
Right-click on the trigger name in the sidebar under the Triggers section to display the context menu. Select Delete from the context menu options to initiate the trigger deletion process.
A confirmation dialog appears requesting verification of the deletion operation. Confirm the deletion to remove the trigger from the sidebar navigation and mark it for deletion in the system.
Recovery from Recycle Bin
Deleted triggers can be recovered from the Recycle Bin if deletion was accidental or the trigger is needed again. The Recycle Bin provides a safety mechanism for recovering deleted triggers before permanent removal.
Recycle Bin Access: Access the Recycle Bin through the Setup menu in the administrative interface. Navigate to the appropriate section for triggers or code files to locate deleted triggers.
Recovery Process: Select the deleted trigger in the Recycle Bin and use the restore function to return it to the active triggers list. Restored triggers reappear in the sidebar navigation tree and can be opened and edited normally.
Restoration Effects: Restored triggers resume automatic execution when appropriate data operations occur on their associated entities. No additional configuration is necessary beyond restoration to reactivate trigger functionality.
Deletion Impact Considerations
Business Rule Removal: Deleting triggers removes automated business rules, validation logic, and automated processes from the system. Verify that trigger functionality is no longer required or has been replaced by alternative implementations before deletion.
Data Integrity: Consider whether trigger deletion impacts data integrity, required field calculations, or dependent automated processes. Some triggers implement critical business rules whose removal could allow invalid data or break dependent workflows.
Testing After Deletion: After deleting triggers, test entity data operations to verify that expected behavior continues without the deleted trigger. Ensure that no required functionality was lost and that data operations complete successfully without errors.
Trigger Use Cases and Examples
Data Validation and Integrity
Triggers enforce complex validation rules that cannot be implemented through standard field validation including cross-field validation, conditional requirements based on other field values, validation against related record data, external system validation, and complex business rule enforcement.
Example - Conditional Required Fields: Validate that certain fields are populated when other fields have specific values, such as requiring close date when opportunity stage is "Closed Won" or requiring reason code when case status is "Closed."
Example - Relationship Validation: Verify that related records exist, have appropriate status values, or meet specific criteria before allowing record creation or updates. Prevent orphaned records or invalid relationship configurations.
Example - Duplicate Prevention: Check for existing records with matching key fields before allowing new record creation. Prevent duplicate accounts, contacts, or other entities based on organizational duplicate criteria.
Calculated Field Updates
Triggers calculate and update field values automatically based on other field values, related record data, or complex formulas that exceed standard formula field capabilities.
Example - Rollup Calculations: Calculate sum, count, or average values from related child records and update fields on parent records. Maintain summary statistics without requiring manual recalculation.
Example - Derived Values: Compute derived field values based on multiple input fields using complex formulas, lookups, or conditional logic. Keep calculated fields synchronized with source data automatically.
Example - Status Determination: Determine and update status fields based on complex conditions involving multiple fields, related records, dates, or business rules. Ensure status fields accurately reflect current record state.
Automated Notifications
Triggers send email notifications automatically when significant events occur, keeping stakeholders informed without manual notification processes.
Example - Assignment Notifications: Send email notifications to users when records are assigned to them, including record details and links for quick access. Ensure assignees are immediately aware of new responsibilities.
Example - Status Change Notifications: Notify stakeholders when record status changes to specific values such as case escalation, opportunity closure, or approval completion. Enable timely responses to important state changes.
Example - Threshold Alerts: Send alerts when field values exceed thresholds, violate limits, or meet specific criteria. Enable proactive management of exceptions and critical conditions.
Related Record Management
Triggers create, update, or delete related records automatically to maintain data relationships, implement master-detail cascading behavior, or ensure required related data exists.
Example - Automatic Child Record Creation: Create required child records automatically when parent records are created, such as creating default line items for opportunities or creating initial activity records for new projects.
Example - Cascading Updates: Update related child records when parent record fields change, maintaining consistency across the relationship. Propagate status changes, ownership updates, or field value changes to dependent records.
Example - Cleanup on Deletion: Delete related records when parent records are deleted to prevent orphaned child records. Implement cascading delete behavior for records that should not exist without their parent.
Integration and External System Synchronization
Triggers initiate integration processes that synchronize data with external systems, notify external applications of changes, or trigger webhooks for real-time integration patterns.
Example - Real-Time Synchronization: Send updated record data to external systems immediately when changes occur, maintaining synchronized data across platforms without scheduled batch processes.
Example - Webhook Notifications: Invoke external webhook URLs when specific events occur, enabling external systems to respond to Magentrix data changes in real-time.
Example - Queue for Batch Processing: Add records to processing queues when specific conditions are met, enabling batch integration processes to handle records requiring external system interaction.
Webhook Integration and Real-Time Data Synchronization
Triggers provide an ideal mechanism for invoking webhooks on external platforms, enabling real-time integration patterns that notify external systems immediately when data changes occur in Magentrix without requiring scheduled batch processes or manual synchronization.
Example - External System Notifications: Trigger webhooks to external systems immediately when critical records are created or updated, such as notifying a fulfillment system when orders are placed, alerting a marketing automation platform when leads are qualified, or updating an accounting system when invoices are generated.
Example - Third-Party Service Integration: Invoke third-party service APIs through webhook calls when specific conditions are met, such as triggering payment processing when order status changes to "Ready for Payment," initiating shipping label generation when orders are approved, or requesting credit checks when account values exceed thresholds.
Example - Cross-Platform Synchronization: Maintain synchronized data across multiple platforms by triggering webhooks that update external systems with Magentrix data changes, such as synchronizing customer information with CRM systems, updating inventory levels in e-commerce platforms, or maintaining contact lists in email marketing platforms.
Example - Event-Driven Workflows: Initiate complex multi-system workflows through webhook invocations, such as triggering document generation services when contracts are signed, initiating background verification processes when applications are submitted, or starting approval workflows in external workflow management systems.
Implementation Considerations: When implementing webhook calls in triggers, include appropriate error handling for network failures, implement retry logic for transient errors, log webhook invocation results for troubleshooting, validate webhook responses to confirm successful processing, and consider asynchronous patterns for long-running external operations to avoid trigger timeout issues.
Best Practices and Recommendations
Performance Considerations
Minimize Database Operations: Reduce the number of database queries and DML operations in trigger logic. Excessive database operations in triggers impact overall system performance when processing large record sets.
Bulk Operation Handling: Design trigger logic to handle multiple records efficiently using collections and bulk operations rather than processing records individually. Bulk processing reduces database round trips and improves performance.
Avoid Recursive Triggers: Prevent triggers from updating the same records that triggered them, which can cause infinite recursion. Implement recursion prevention using static flags or context checking when trigger logic must update triggering records.
Conditional Execution: Include conditional logic that skips unnecessary processing when trigger logic does not apply to specific records. Conditional execution reduces wasted processing and improves performance for records not requiring trigger functionality.
Error Handling and Logging
Comprehensive Error Handling: Implement try-catch blocks around operations that may fail including database operations, external API calls, and complex calculations. Graceful error handling prevents transaction rollbacks from unexpected errors.
Meaningful Error Messages: When validation fails or business rules are violated, throw exceptions with clear, actionable error messages that help users understand what went wrong and how to correct issues. Avoid technical jargon in user-facing error messages.
Debug Logging: Use Event Log statements during trigger development to trace execution flow, verify field values, and identify where logic deviates from expected behavior. Remove or disable logging statements after debugging to prevent performance impacts.
Selective Transaction Rollback: Determine which errors should prevent the entire operation (throw exceptions) versus which errors should be logged while allowing the operation to proceed. Not all validation failures necessarily require transaction rollback.
Code Organization and Maintainability
Single Responsibility: Each trigger should focus on a specific aspect of business logic such as validation, notification, calculation, or related record management. Focused triggers improve maintainability and enable selective modification.
Leverage Classes: Extract complex business logic, utility functions, and reusable operations into classes that triggers call. Class-based logic enables reuse across multiple triggers and supports independent testing.
Clear Comments: Include comments explaining business rules, validation logic, calculation formulas, and non-obvious implementation details. Documentation reduces maintenance time and prevents misunderstandings about trigger intent.
Consistent Patterns: Use consistent implementation patterns across triggers for similar operations. Consistency improves code readability and enables developers to understand trigger logic quickly based on familiar patterns.
Testing and Validation
Comprehensive Testing: Test triggers thoroughly with various data scenarios including valid data, invalid data, edge cases, bulk operations, and combinations of field values. Comprehensive testing ensures triggers handle all scenarios correctly.
Bulk Operation Testing: Verify trigger behavior when processing multiple records simultaneously. Bulk operations may expose performance issues or logic errors not apparent when testing with single records.
Error Scenario Testing: Test validation logic and error handling by deliberately attempting to create or update records that violate business rules. Verify that appropriate error messages appear and transactions roll back correctly.
Integration Testing: When triggers interact with external systems, test integration points thoroughly including success scenarios, failure scenarios, timeout handling, and data format validation.
Security and Authorization
Authorization Verification: Verify user permissions and authorization before performing sensitive operations in triggers. Respect organizational security model and access controls even in automated processes.
Data Security: Handle sensitive data appropriately in triggers including proper encryption, logging practices that avoid exposing sensitive information, and compliance with data protection requirements.
Audit Trail: Consider implementing audit logging for important trigger operations enabling tracking of automated changes, compliance verification, and troubleshooting of unexpected behavior.
Jump to IDE Checklist
<< Working with Controllers and Classes | Managing Static Assets >>