Trigger.New in Salesforce Apex

In Salesforce, Apex triggers are used to automate processes and apply custom logic during specific database operations, such as insert, update, delete, and undelete.

In that, we use this Trigger.New, which is one of the types of context variables, is used to return a list of the new version of sObject records.

In this Salesforce tutorial, we will learn about Trigger.New in Salesforce Apex, which is one of the types of context variables in the trigger.

In that, I will explain what is context variables and Trigger.New in Apex Trigger, its uses, and then we will see how to use Trigger.New context variable in trigger Apex code.

Trigger Context Variable in Salesforce Apex

Trigger context variables in Salesforce Apex provide information about the records that activate the trigger and the conditions under which the trigger was executed.

These variables allow developers to access inserted, updated, deleted, or undeleted records and perform actions based on that context.

What is Trigger.New in Salesforce Apex?

In Apex Triggers, Trigger.New is a context variable that provides access to the new records being processed in an insert or update operation.

It is a list of sObject records that are available during a trigger’s execution and represents the records as they exist in the database after the operation has been initiated.

To create records, Trigger.New contains all the records that are being inserted, and for update records, there is also the Trigger.New contains all the new values of the records after the update operation.

  • In the after trigger event, Trigger.New is read-only because the records have already been created in the database.
  • We can only use the Trigger.New context variable with before insert, before update, after insert, and after update trigger events.
  • In the before trigger event, Trigger.New is editable, allowing us to modify field values before the records are saved to the database.
  • Trigger.New is not available in delete triggers because deleted records are handled by the Trigger.Old context variable.

Syntax: Declaring Trigger.new Context Variable

List<sObject> Trigger.New

Trigger.New is a list of the sObject type that is related to the object on which the trigger is defined.

Example: Use Trigger.New with Before Insert Event in Apex

For example, whenever I create an account record, the other fields where I want to set default values should get automatically saved. In the below apex code, I will explain how we can do that.

Here, I’m using the before insert trigger event because we are updating fields in the same object as the new account record is created.

Then, in each loop, we declare Trigger.new, which returns the list of new records on which we are trying to perform a DML operation.

In the for loop, I assigned some values to the account fields so that when we create the account record and don’t fill these fields after creating the record, the assigned value will be automatically added to the record.

Here, I added logic in the trigger itself. But the trigger should be logic-less for that, so we create a trigger helper and a handler class.

trigger AccountTrigger on Account (before insert) {
       for (Account acc: Trigger.new) {
           acc.Active__c = 'Active';
           acc.Rating = 'Hot';
      }
}

Here, you can see I only filled out the account name field and saved the record directly.

Trigger.new in Salesforce Apex

As you save the record and open the account details, you can see the values we assigned in the Apex trigger code displayed in the account details.

Trigger Context Variable in Salesforce Apex

Example: Use Trigger.New with After Insert Event in Apex

For example, when a new contact record is created, and the lead source is ‘Web’ from the contact record, then create a new task record and assign the newly created task to the contact owner.

To create new task records when contact records are created, we need to create a trigger on the contact object. We also need to use the after-insert trigger event. First, we created a list collection of task objects, which will store the value of the fields of the task objects.

Then in the for each loop, we created a contact object instance and assigned Trigger.New to that instance, so that whenever a new record is created on the contact object, it will get assigned to the contact object instance.

Then, in the if statement, we added the condition if the lead source of the contact record is the web, then only process to the next step.

If the lead source is the web, then in the next step, we add the information of task object fields, and we also want to assign that task to the contact owner themselves.

Finally, we created a record for the task object using the Insert DML operation. Save the trigger and then navigate to the contact object to verify whether the task is created after a contact is created.

trigger ContactTrigger on Contact ( after insert ) {
    
         List<Task> tasksToCreate = new List<Task>();
    
         for ( Contact con : Trigger.New ) {
                  if ( con.LeadSource == 'Web' ) {
                          tasksToCreate.add (new Task (
                          Subject = 'Follow-up with web contact',
                          Status = 'Not Started',
                          Priority = 'High',
                          OwnerId = con.OwnerId
                      ));
                }
         }
    
        if ( !tasksToCreate.isEmpty() ) {
            insert tasksToCreate;
         }
}             

Here, I’m creating the contact record with the lead source as ‘Web’ and the contact owner as ‘Alex Kirk’. Now, when this record gets created, the task record should also be created and assigned to the contact owner.

Click the Save button to create the contact record.

Use Trigger.New in Salesforce Apex

After the contact record is saved, navigate to the Task object to verify that the new task is created with the values provided in the trigger code.

In the image below, you can see that the task record has been created with the same values we provided, and it has also been assigned to the contact owner.

Use Trigger.New with after insert event in Salesforce Apex

In this way, we can use Trigger.New with the after insert trigger event in Salesforce Apex.

Example: Use Trigger.New with After Update Event in Apex

In Salesforce, the account and contact are in a lookup relationship, and the account is the parent object of contact, and one account can have multiple associated contact records.

For example, when the ‘Account Priority‘ is updated, we want to update all related contacts ‘Contacts Priority’ field’s value to the same as the updated account priority.

In the above example, when the account is updated, the associated contact record should also be updated.

For that, we need to create a trigger on the account object. The trigger event will be after the update because we want to update fields from different objects.

First, we created a list collection that will store the contact records, which will be updated. In for each loop, we created sObject and assigned Trigger.New context variable so that whenever any already created account record ID is being updated, it will get assigned to the sObject.

After that, we created an account variable and assigned Trigger.OldMap.get(acc.Id) to the variable. The Trigger.OldMap is also the type of trigger context variable that is used to access the old values of a record in a trigger.

Now, in the if statement, we checked if the old value of account priority is not equal to the new value of account priority. If it is not equal, then that field will be updated.

Again in the, for each loop, define the contact sObject. Then, I retrieved the contact IDs associated with the updated accounts and assigned them to sObject. After that, assign the value of the updated account priority field from the account object to the contact priority field in the contact object.

Add the contact record to the list using the add() method that we created, and lastly, use the update DML operation to save changes to the contact record.

trigger UpdateContact on Account (after update) {
    
        List<Contact> contactsToUpdate = new List<Contact>();
    
        for ( Account acc : Trigger.New ) {
                  Account oldAcc = Trigger.OldMap.get (acc.Id);

                  if ( oldAcc.Account_Priority__c != acc.Account_Priority__c ) {

                            for ( Contact con : [SELECT Id FROM Contact WHERE AccountId = :acc.Id] )      
                             {
                                     con.Contact_Priority__c = acc.Account_Priority__c ;
                                    contactsToUpdate.add(con);
                             }
                     }
            }
    
         if ( !contactsToUpdate.isEmpty() ) {
                 update contactsToUpdate;
          }
}

Now, here you can see I already created an account record in which the account priority field is blank.

Trigger.New Context Variable in Salesforce Apex

Let’s check the contact associated with that account; the contact priority field is also blank here.

Trigger.New Context Variable in Apex Trigger

Now, let’s update the account priority field from the account object record and Save the changes.

Trigger.New Context Variable in Apex

After updating the account record, you can see the contact priority field also gets updated automatically with the same value as the account priority field.

Trigger.New with after update trigger event in Apex

In this way, we can use Trigger.New content variable in Salesforce Apex triggers to get access to the new records being processed in an insert or update operation.

Conclusion

I hope you have got an idea about Trigger.New in Salesforce Apex, which is one of the types of context variables in the trigger. In that, I have explained what is context variables and Triggers.New in Apex Trigger, its uses and then we have seen how to use Trigger.New context variable with different trigger events in Apex trigger code with different examples and explanations.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.