I am trying to create an Apex trigger that will create a contact using the SuppliedEmail field of a case to avoid situations where we have a case that is not tied to an account (we will need all cases to be tied to accounts in order to implement SLAs via Entitlements). I found this answer: https://developer.salesforce.com/forums/?id=906F00000009CSkIAM however I would really like to understand what is wrong with what I am doing as I will need to develop further features and it feels like I'm just not getting something very important about the whole system.
Here is my code:
trigger new_case_handling on Case (before insert) {
System.debug('Entered execution procedure for new_case_handling trigger');
for (Case receivedCase: Trigger.new) {
Boolean contactCreated = false;
if(receivedCase.AccountId == null && receivedCase.SuppliedEmail != null) {
List<Account> unknownAccount = [SELECT Id FROM Account WHERE Name = 'UNKNOWN ACCOUNT'];
if(unknownAccount.size() != 0) {
String fullEmail = String.valueOf(receivedCase.SuppliedEmail);
String newUsername = 'NOTAVAILABLE';
if(fullEmail.indexOf('@') != -1) {
newUsername = fullEmail.split('@').get(0);
}
Contact newContact = new Contact(
LastName = newUsername,
Email = receivedCase.SuppliedEmail,
AccountId = unknownAccount[0].Id);
insert newContact;
contactCreated = true;
System.debug('Created contact ' + String.valueOf(receivedCase.SuppliedEmail) + ' on account ' + unknownAccount[0].Id );
}
else {
System.debug('Unable to find UNKNOWN ACCOUNT to insert ' + String.valueOf(receivedCase.SuppliedEmail) + 'in' );
}
if(contactCreated) {
List<Contact> createdContact = [SELECT Id FROM contact WHERE Email =:receivedCase.SuppliedEmail];
if(createdContact.size() > 0){
receivedCase.contactId = createdContact[0].Id;
insert receivedCase;
}
else {
System.debug('Contact was created but query failed.');
}
}
}
}
}
When I set the trigger condition to before update
and try to modify a case that came from an unregistered email address, it seems to work out totally fine -- it creates the contact on the UNKNOWN ACCOUNT account and assigns it to the ticket. However before insert
doesn't seem to work at all, I am not able to see any logs in the Developer Console (although I am perhaps not looking for them properly), and the case does not end up being created at all(!). Can you guys please guide me toward what I am missing?