function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mw6mw6 

Auto create a contact from Case created by web-to-case, if the contact is not existing

Hi I have created below trigger to create the contact when a case is inserted via web-to-case.  There is no error, and I am not sure why the contact is not getting created.  I have only one custom field on contact to mark as auto created, rest all are standard fields. Can anybody help to figure out the issue.. 

trigger AutocreateContactfromCase on Case (before insert) {
    List<String> emailAddresses = new List<String>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedEmail!='')
        {
            emailAddresses.add(caseObj.SuppliedEmail);
             
        }
    }
    List<Contact> listContacts = [Select Id, Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null &&
            caseObj.SuppliedName!=null &&
            caseObj.SuppliedName!='' &&
            caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!='' &&             
            caseObj.SuppliedPhone!=null &&
            caseObj.SuppliedPhone!='' &&            
            !takenEmails.contains(caseObj.SuppliedEmail))
         {
            String[] nameParts = caseObj.SuppliedName.split(' ',2);
            if (nameParts.size() == 2)
            {
                Contact cont = new Contact(FirstName=nameParts[0],
                                            LastName=nameParts[1],
                                            Email=caseObj.SuppliedEmail,
                                            Phone=caseObj.SuppliedPhone,
                                            Autocreated__c=true);
                emailToContactMap.put(caseObj.SuppliedEmail,cont);
                casesToUpdate.add(caseObj);
            }
        }
    }
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
        caseObj.ContactId = newContact.Id;
    }
}
 
buggs sfdcbuggs sfdc
i think you should try after event trigger
trigger AutocreateContactfromCase on Case (after insert) {
surojit Mondalsurojit Mondal
Hi MW6,

Execute the above snippet in after trigger context as you are performing DML on related list.

Regards,
Surojit