function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DustinLHDustinLH 

Too Many DML Statements - Small Trigger

I am getting an error with Too Many DML Statements for a small trigger that I wrote. I know that it has to do with the insert being inside the loop, but I cannot figure out how to correctly write this. I am hoping someone can take a look since it is so small.

 

trigger ReferralChatterFollow on Referral__c (after insert) {

    for(Referral__c r: Trigger.New) {
                    EntitySubscription follow = new EntitySubscription (
                        parentId = r.id,
                        subscriberId = UserInfo.getUserId());
                    insert follow;
    }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
Nisse Knudsen.ax1026Nisse Knudsen.ax1026

You have to insert all EntitiySubscriptions at once, so you avoid too many DML statements, issued by the INSERT statement inside your loop:

 

trigger ReferralChatterFollow on Referral__c (after insert) {
    
    List<EntitySubscription> allES = new List<EntitySubscription>();

    for(Referral__c r: Trigger.New) {
                    EntitySubscription follow = new EntitySubscription (
                        parentId = r.id,
                        subscriberId = UserInfo.getUserId());
                    allES.add(follow);
    }

    if(!allES.isEmpty()) {
       insert allES
   }
}

 

All Answers

Nisse Knudsen.ax1026Nisse Knudsen.ax1026

You have to insert all EntitiySubscriptions at once, so you avoid too many DML statements, issued by the INSERT statement inside your loop:

 

trigger ReferralChatterFollow on Referral__c (after insert) {
    
    List<EntitySubscription> allES = new List<EntitySubscription>();

    for(Referral__c r: Trigger.New) {
                    EntitySubscription follow = new EntitySubscription (
                        parentId = r.id,
                        subscriberId = UserInfo.getUserId());
                    allES.add(follow);
    }

    if(!allES.isEmpty()) {
       insert allES
   }
}

 

This was selected as the best answer
DustinLHDustinLH

This works perfectly, thank you so much! I would buy you a drink for all of your help with this project, but you live too far away!