SELF_REFERENCE_FROM_TRIGGER Exception in Salesforce

SELF_REFERENCE_FROM_TRIGGER Exception in Salesforce

SELF_REFERENCE_FROM_TRIGGER error or exception from Salesforce Apex indicates that a DML operation like update or delete on a record is already being updated by another trigger. So, it throws this exception.

Reference Article:
https://help.salesforce.com/s/articleView?id=000324391&type=1

Sample Apex Triggers to reproduce the issue:

Trigger on Account:

trigger AccountTrigger on Account ( before update ) {

    Contact objContact = new Contact(
        FirstName = ‘Testing 1’,
        LastName = ‘Testing 2’,
        AccountId = trigger.new.get( 0 ).Id
    );
    insert objContact;

}

Trigger on Contact:

trigger ContactTrigger on Contact ( after insert ) {

    if ( String.isNotBlank( trigger.new.get( 0 ).AccountId ) ) {

        update new Account(
            Id = trigger.new.get( 0 ).AccountId,
            Description = ‘Testing’
        );

    }

}

Error or Exception:

Trigger Example with Roll-Up Summary Field:

Roll-Up Summary Field:

Sample Trigger:

trigger AccountTrigger on Account ( before update ) {

    Opportunity objOpportunity = [
        SELECT Id, StageName, AccountId
        FROM Opportunity
        WHERE AccountId =: trigger.new.get( 0 ).Id LIMIT 1
    ];
    objOpportunity.StageName = 'Qualification';
    objOpportunity.AccountId = '0018c00002MANWYAA5';
    update objOpportunity;
    System.debug( 'Opportunity Updated' );

}

When the Account is updated, one of its Opportunity is fetched and its Account Id is changed to hard coded Account Id. After the Account Id change, the whole save process will start again since the Roll-Up Summary field will be recalculated.

Note:

As per the order of execution in Salesforce, “If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.” It will do the Save Procedure again due to Roll-Up calculation. So, in before trigger context, avoid updating records which will recalculate the Roll-Up calculation.

Leave a Reply