+ Start a Discussion
Will Jones 18Will Jones 18 

Need to confirm a trigger isn't causing a Too Many DML Statements error

I am newer to writing triggers and I am not sure if the code below is causing me to receive the infamous Too Many DML Statements 151. Is it not bulkified correctly?

I took this code from what I saw online and just applied it to my situation. Essentially I needed to take the primary contact from my opportunity contact role and place it in a look field on the opportunity page so that I can look at it for workflows and such. Thanks in advance.
trigger InsertPrimaryContact on Opportunity (before insert, before update) {

Set<Id> OppIds = new Set<Id>();
for (Opportunity o : Trigger.new) {

Map<Id, List<OpportunityContactRole>> Opp_OCR = new Map<Id, List<OpportunityContactRole>>();

for (OpportunityContactRole oppocr : [select id, ContactId, Opportunityid, isPrimary from 
    OpportunityContactRole where opportunityid in :OppIds and isPrimary = true]) {

    List<OpportunityContactRole> tmp_oppocr = new List<OpportunityContactRole>();

    tmp_oppocr = Opp_OCR.get(oppocr.opportunityid);

    if (tmp_oppocr == null) {
        Opp_OCR.put(oppocr.opportunityid, new List<OpportunityContactRole>{oppocr});
    else {

        Opp_OCR.put(oppocr.opportunityid, tmp_oppocr);

system.debug('Final Opp_OCR map: '+Opp_OCR);

for (Opportunity opps : Trigger.new) {
    List<OpportunityContactRole> this_oppocr = new List<OpportunityContactRole>();
    this_oppocr = Opp_OCR.get(opps.id);
    system.debug('this Opps ('+opps.id+') list of oppocrs: '+this_oppocr);

    if (this_oppocr == null) {
        opps.Primary_Contact__c = null;
    else {

        for (OpportunityContactRole r : this_oppocr) {
            if (r.isprimary) 
                opps.Primary_Contact__c = r.ContactId;


ShashankShashank (Salesforce Developers) 
There isn't a single DML statement in this trigger (advantage of a "before" trigger) so it would not hit the DML statement limit. If you are hitting the limit, you would usually get to see the name of the triggger as well which is causing the limit error.
Grazitti TeamGrazitti Team
Hi Will,

I don't see any major issue in your code except at line 43. It's not good practice to use 'for loop' inside another 'for loop'. I would suggest you to check debug log for the limit error you have mentioned above.

Please mark this as best answer if it helps.

Grazitti Team.
Will Jones 18Will Jones 18
Thanks for the responses.

@Shashank what is weird is the the name of the trigger is Hubspot (the marketing tool).

First error: HubSpot_Inc:Too many DML statements: 151

I was wondering if something in my code was causing this or is this a Hubspot issue. Since Hubspot is a managed package I can't see their code. Not sure who should be working to solve it. Me or Hubspot?
ShashankShashank (Salesforce Developers) 
Since we cannot see the HubSpot code, I would recommend you to reach out to HubSpot regarding this.