The Trigger.size variable in Apex triggers is used to determine the total number of records in a trigger invocation, including both old and new records. It provides the count of records that caused the trigger to fire.
Here are a few reasons why Trigger.size is commonly used in Apex triggers:
•\ Bulk Processing: Apex triggers are designed to handle bulk operations, where multiple records are processed simultaneously. By using Trigger.size, you can perform validations or actions based on the number of records being processed. For example, you can enforce limits on the number of records that can be inserted or updated at once. It allows you also to process records in batches, which can help you stay within Salesforce governor limits as in the next example here.
•\ Governor Limits: Salesforce imposes various governor limits to ensure the efficient use of resources. These limits include the number of records processed in a single transaction. By using Trigger.size, you can monitor and control the number of records being processed to avoid hitting these limits.
•\ Recursion Handling: In some cases, triggers can cause recursion, where a trigger invokes itself repeatedly. By using Trigger.size, you can implement logic to handle recursion and prevent infinite loops. For example, you can set a static variable to track the number of times the trigger has executed and use Trigger.size to check if it’s the first execution or a subsequent one.
It’s important to note that Trigger.size represents the total number of records in a trigger invocation, not just the number of records being inserted or updated. Therefore, it can be used to handle various scenarios and implement logic based on the number of records involved.
Suppose you want to track changes made to a specific custom field on an object. Whenever that field is modified, you want to create a history record that captures the old and new values of the field. You can use the Trigger.oldMap context variable to access the previous values of the field and compare them with the new values in Trigger.new.
Step 1: Go to Setup ➤ Object Manager tab. Click the “Create” button ➤ Custom Object. Create new custom object with name “History” and save. After creating the new object, the API name will be set automatically to History__c.
Step 2: Create four new custom fields on the History__c custom object as follows by going to Setup ➤ Object Manager tab. Click History object ➤ Fields and Relationships on the left menu. Click “New” button to create new field.
Object_Id: Lookup to the Lead object
Field_Name: Text field to store the API name of the field being tracked
Old_Value: Text field to store the old value of the tracked field
New_Value: Text field to store the new value of the tracked field
Step 3: Go to Setup ➤ Type Tabs in the search field on the left menu in the area Custom Object Tabs. Click the button “New” to add and make new created customer object History__c visible in your Salesforce App Launcher.