You need to sign in to do that
Don't have an account?
Medhanie Habte 37
Bulkify a trigger to assign WhoId from an Email Message to a Task
Greetings, I've created this trigger which creates a task each time an email message is sent. Now I understand that may result in a duplicate task as email messages create tasks, but we wanted to figure a workaround that will allow creating tasks that can be populated on some custom fields and reports we have specific to a business process.
I feel good about what we have, but am wondering if there is a way to bulify the trigger by moving the SOQL query into a list, so I don't have to query within the trigger?
trigger EmailToTask on EmailMessage (after insert) { for (EmailMessage e : Trigger.new) { if (e.RelatedToId != NULL) { Task t = new Task(); t.ActivityDate = date.today(); t.Description = e.TextBody; t.Move_Type__c = 'Personal Note/Email from Donor'; t.Priority = 'Normal'; t.Status = 'Completed'; t.Subject = e.Subject; t.WhatId = e.RelatedToId; t.WhoId = [SELECT Id FROM Contact WHERE Email = :e.ToAddress OR npe01__WorkEmail__c = :e.ToAddress OR npe01__HomeEmail__c = :e.ToAddress].Id; insert t; } } }
No problem, I was able to bulkify my trigger by creating a list, then going for a map which based on the SOQL query prints the email address associated with a matching contact Id, querying for a home, work and preferred email address. I achieved 100% code coverage with it.
All Answers
You can add task in list and insert that list ouside for loop to make it bulkify. Also don't write query inside for loop
Let me know if you need any help.
Thanks,
Sukanya Banekar
if(string.valueOf(con.Email).isNotBlank)
mapEmail.put(con.Email,con.Id);
Is there anything else I should add.
For if string, the .isNotBlank should be populated in string.IsNotBlank
Incorrect
if(string.valueOf(con.Email).isNotBlank)
mapEmail.put(con.Email,con.Id);
Correct
if(string.isNotBlank(con.Email))
mapEmail.put(con.Email,con.Id);
Yes, I didnot check with the syntax and just posted the answer.
No problem, I was able to bulkify my trigger by creating a list, then going for a map which based on the SOQL query prints the email address associated with a matching contact Id, querying for a home, work and preferred email address. I achieved 100% code coverage with it.