+ Start a Discussion
gladmin1.3926277599775933E12gladmin1.3926277599775933E12 

After Update system.LimitException over the weekend, bulkify?

Hi,

I have the below triggr to add in a contact to a contact role, whenever a contact is created and the account name  is the same as the opportunity name. It works fine but over the wwkened it threw ut a loan of LimitExceptions...I assume this was due to some Salesforce batch process, as it wasn't anything we were running. Nevertherless it highlights an issue with the code.
I have looked a blulkifacation, but can't see how I would get this inplace. 

Any thoughts?

Thx

trigger UpdateRoles on Opportunity (after insert, after update)
{
    for (Opportunity triggerOpportunity : Trigger.new)
    { 
        for(Contact contact : [Select ApplicantType__c from Contact where AccountId =: triggerOpportunity.AccountId and IsActive__c =: true])
        {
             if (contact.ApplicantType__c == 'Guarantor')
                {
              LIST<OpportunityContactRole> CR = [Select ContactId from OpportunityContactRole where OpportunityId =: triggerOpportunity.Id and Role =: 'Guarantor'];
             
                  if (CR.isEmpty())
                        {
                            OpportunityContactRole OCR = new OpportunityContactRole(OpportunityId = triggeropportunity.Id, ContactId = contact.id, Role = contact.ApplicantType__c, IsPrimary = false);
                            insert OCR;
                        }
                   
                }
        }
    }

}
GunnarGunnar
This line here is killing you...

*** for(Contact contact : [Select ApplicantType__c from Contact where AccountId =: triggerOpportunity.AccountId and IsActive__c =:

You have a SELECT inside of a FOR loop. I would not do that. Get your keys before you enter loops.