You need to sign in to do that
Don't have an account?
wedaft
Having trouble bulkifying this trigger
Hi all,
I'm creating a trigger that should update a field on a custom object called "COTM Protocols" whenever an email with a certain subject is sent to the contact related to that protocol. I had the trigger working fine, but I had a SOQL query inside a FOR loop so I have to bulkify it. I'm giving it my best shot, but can't seem to make it work. No error messages, but the field isn't updating the way it's supposed to. Here's my code:
trigger UpdateCOemaildateOnProtocol on Task (after insert) { List<task> tasks = trigger.new; //Get list of Teacher IDs List<Id> teacher_ids = new List<Id>(); for (task t : tasks){ teacher_ids.add(t.WhoId); } //Produce data for protocols List<COTM_Protocol__c> protocols = [SELECT id, CO_Follow_up_sent_trigger__c, CO_number__c, subject__c, Teacher_Implementation__r.Name FROM COTM_Protocol__c WHERE Teacher_Implementation__r.Name LIKE '%2012-2013' ]; for (task t : tasks){ for (COTM_protocol__c p: protocols){ if (t.CO_number__c == p.CO_number__c) if (t.WhoId == p.subject__c) if (p.Teacher_Implementation__r.Name.contains('2012-2013')) if (p.CO_Follow_up_sent_trigger__c == null){ p.CO_Follow_up_sent_trigger__c = t.ActivityDate; p.CO_email_sent__c = true; } } } //update the protocol update protocols; }
Thank you!
I don't think there's enough information to know for sure what is happening here. But your debugging steps are clear:
Use some System.Debug statements to check the values of the t and p objects so you can see why the comparison isn't being matched (which is the logical reason why you're not seeing an update. Check the debug log to see if you are even retrieving any rows.
Dump the nested if statements and use the && operator (And) instead - the code will be much easier to understand.
Add CO_email_sent__c to the query term as well.
Why are you creating a list teacher_ids? You aren't using it.
Depending on the nature of the relationships, there may be ways to make the code more efficient, but whether that's really necessary depends on the number of tasks and protocols.
At this point - use the debug log or debugging console to see what is actually happening (you do have a test class right? If not - write a test class so you can debug this code).
Dan