You need to sign in to do that
Don't have an account?
What could be wrong with this triggers?
I have the following trigger which checks off the Executive for every new Case based on the Executive value in Contacts.
trigger Executive on Case (before insert, before update) { Map<Id, Case[]> contactCaseMap = new Map<Id, Case[]>(); For (Case ncase:Trigger.new) { Id cid = ncase.contactId; If (cid != NULL) { if(contactCaseMap.get(cid) == null) contactCaseMap.put(cid, new Case[]{}); contactCaseMap.get(cid).add(ncase); } } For(Contact c:[select Executive__c from Contact where Id IN :contactCaseMap.keySet()]) { for(Case ncase:contactCaseMap.get(c.id)) { ncase.Executive__c = c.Executive__c; } } }
It works fine except that every now and then I get following exception in email from Production.
Apex script unhandled trigger exception by user/organization: xxxxxxxxxxxxx/xxxxxxxxxxxx
Executive: execution of BeforeInsert
caused by: System.Exception: Too many SOQL queries: 21
Trigger.Executive: line 12, column 17
But I dont see what wrong with my code. Nevertheless, I changed the code to following avoiding many for loops:
trigger Executive on Case (before insert, before update) { Map<Id, Case[]> contactCaseMap = new Map<Id, Case[]>(); Id cid; Contact d = new Contact(); for (Case ncase:Trigger.new) { cid = ncase.contactId; if (cid != NULL) { if(contactCaseMap.get(cid) == null) contactCaseMap.put(cid, new Case[]{}); contactCaseMap.get(cid).add(ncase); } } if (cid != NULL) { list<Contact> c = [select Executive__c from Contact where Id IN :contactCaseMap.keySet() limit 1]; if (c.size()!=0) {d=c[0];} Trigger.new[0].Executive__c = d.Executive__c; } }
But I get the same exact exception still every other day. I am not able to understand whats going wrong. Any help?
Your getting the exception because you trigger is not setup to work in bulk. Please review this post.
Then reply back with questions, also you might want to read the section of the docs that explains bulk operations.