+ Start a Discussion
mallikammallikam 

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?
mikefmikef

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.

mallikammallikam
thanks!!  I realized that it has to do with my Map and I also realized that I need not have to use Map in this case?! I wrote something simple and deployed it.