The evaluate method is called upon the occurrence of a real-time event monitored by a transaction security policy. A typical implementation first selects the fields of interest from the event. Then the fields are tested to see if they meet the conditions being monitored. If the conditions are met, the method returns true.
For example, imagine a transaction security policy that triggers when a user queries more than 1,000 lead records. For each API event, the evaluate method checks whether the RowsProcessed value is greater than 1,000 and the QueriedEntities value contains “Lead”. If so, true is returned.
We recommend having test classes for the policy condition interface to ensure it works correctly. Testing is required regardless of whether the policy is moved from a sandbox to production, with a change set, or some other way. For example, test your policies in your development environment before moving the policies to production.
Don’t include DML statements in your custom policies because they can cause errors. When you send a custom email via Apex during transaction policy evaluation, you get an error, even if the record is not explicitly related to another record. For more information, see Apex DML Operations in the Apex Developer Guide.
The following are methods for EventCondition.
public Boolean evaluate(SObject event)
Type: Boolean
Returns true when the policy is triggered. For example, suppose that the policy is to limit users to a single login session. If a user tries to log in a second time, the policy blocks the attempted login, and updates the Status, PolicyId, and PolicyOutcome fields of that LoginEvent. The policy also sends an email notification to the Salesforce admin. The evaluate method only checks the login event, and returns true if it’s the user’s second login attempt.
The system performs the action and notification, not the evaluate method.
This example shows an implementation of the TxnSecurity.EventCondition interface. The transaction security policy triggers when the user queries an Account object.
global class BlockAccountQueriesEventCondition implements TxnSecurity.EventCondition { public boolean evaluate(SObject event) { switch on event { when ApiEvent apiEvent { return handleApiEvent(apiEvent); } when null { // Trigger action if event is null return true; } when else { // Trigger action for unhandled events return true; } } } private boolean handleApiEvent(ApiEvent apiEvent){ if(apiEvent.QueriedEntities.contains('Account')){ return true; } return false; } }
For more examples, see Enhanced Apex Transaction Security Implementation Examples.