I want to insert multiple cases, which will then send out emails for each case. My EmailMessage Trigger fires for each single email but I want it to only run once.
The method which triggers the Case Insert
public with sharing class createCases {
@AuraEnabled
public static Boolean createCases(List<Case> listofCases) {
List<Case> casesToInsert = new List<Case>();
for (Case c : listofCases) {
casesToInsert.add(new Case(Subject = 'test'));
}
if (!casesToInsert.isEmpty()) {
insert casesToInsert;
return true;
}
}
}
This method is in my isAfter && isInsert case trigger
public static void newCases(List<Case> cases) {
List<Case> myCases = new List<Case>();
List<Messaging.SendEmailResult> emailGroup = new List<Messaging.SendEmailResult>();
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (Case c : myCases) {
myCases.add(c);
}
myCases = new List<Case>([SELECT Id, ContactId FROM Case WHERE Id IN :myCases]);
for (Case c : myCases) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTargetObjectId(c.ContactId);
email.setWhatId(c.Id);
email.setSaveAsActivity(true);
email.setUseSignature(false);
email.setTemplateId(myEmailTemplate.Id);
email.setOrgWideEmailAddressId(myEmailAddress.Id);
emails.add(email);
}
emailGroup.addAll(Messaging.sendEmail(emails));
}
EmailMessageTrigger
trigger EmailMessageTrigger on EmailMessage (before insert, before update, after insert, after update) {
System.debug('Trigger.new: ' + Trigger.new);
}
If I have 50 cases, this fires for each single email, but I only want it to fire once. Basically, I want Trigger.New to contain a List of all the emails, but instead it only contains one.
How should I re-write my newCases method to send out a list of emails? Thanks in advance