You need to sign in to do that
Don't have an account?
Bob
Too many SOQL queries: 101 Trigger_CasePrimaryContact: line 7, column 1
I am having a issue with my trigger. When i try to do a mass update on account records I get this error message. Too many SOQL queries: 101 Trigger_CasePrimaryContact: line 7, column 1
my trigger code is below, any help with issue would be greatly appreciated.
my trigger code is below, any help with issue would be greatly appreciated.
trigger Trigger_CasePrimaryContact on Account (before insert, before update) { for (Account a : Trigger.new) { AccountContactRole[] contactRoleArray = [select ContactID, Role from AccountContactRole where AccountId = :a.id AND Role='Asset Management Service Contact' ]; if (contactRoleArray.size() > 0) { a.Account_Case_Contact__c = contactRoleArray[0].ContactID; }else{ // IF NO CONTACT ROLES EXIST RETURN NULL... a.Account_Case_Contact__c = null; } } }
Take that query out of the for loop. With Apex, you should always plan to do DMLs or Queries outside of a for loop. I know they teach it to you that way in courses, but it's a very bad practice.
Also, since you're dealing with a list on specific records, try getting used to working with Maps.
I would rewrite something like this:
I would caution though, that there could be more than one contact role that fits the asset management service contact, but the way this is written, it will pull the last one in the list of the query.
All Answers
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bestpract.htm
Take that query out of the for loop. With Apex, you should always plan to do DMLs or Queries outside of a for loop. I know they teach it to you that way in courses, but it's a very bad practice.
Also, since you're dealing with a list on specific records, try getting used to working with Maps.
I would rewrite something like this:
I would caution though, that there could be more than one contact role that fits the asset management service contact, but the way this is written, it will pull the last one in the list of the query.
I changed the AccountId IN trigger.new to
IN :Trigger.new
because the trigger was failing. I will look into creating a apex class to handle this soon, but thanks again for your help.